There is a lot of refractoring that needs to be done on the current spring application which I am working on for unittesting.
But we are not suppose to go with refractoring...There is a strict no no from clients.
I would like to create a mock for an " instance created in a class using a new operator". because they didn't go with the
dependency injection.(no setters/constructors).
Below is the code
My Mock Test case: I am creating Mock on the "metastoreDAOManager" as below
As there is no setter/Constructor injection done for "metastoreDAOManager" in searchcontroller.class I am not able to perform the mock on ""MetastoreDAOManager"".
Can you please let me know how to achive mock on the "new operator" created in a class..
We are not allowed for refractoring.
Create a proxy for the below code when getUserPreferenceFromMetastore(request) is called.using spring AOP.Is this the right way:
Since it is an instance variable, you can use reflection. The Spring testing jar even provides a method ReflectionTestUtils to make it easy/one line to inject an instance variable into a class.
But the problem is, even if we create an instance using reflection in the test case this is not going to help!!
Because once the "showForm(MockHttpServletRequest request,MockHttpServletResponse response, BindException arg2)"
method in the SearchController class is called , the below code
MetastoreDAOManager metastoreDAOManager = new MetastoreDAOManager();
will create a new instance.
There by the metastoreDAOManager object created in the testcase will evade.
Please correct me if my understanding is wrong...
Joined: Jun 28, 2010
Tried with jmockit but of no luck.
Came to a conclusion that without refractoring code its tough to go a head.
If you are using spring then you shouldn't really be using the new operator at all, certainly not on any object which is likely be be reused or have other things injected into it (usually you would inject your datasource into your dao).
Your DAO should probably be a class variable as well... since it should be stateless and thus you will only need one instance to hadle all requests...
Here is a very simple snippet to illustrate what I mean:
This makes testing simpler as you can use the test helper classes in Spring to inject a mock metastoreDAOManager and do as you wish.
Hope this makes sense.
I love this place!
Joined: Jun 28, 2010
Thanks for the response!!
As told earlier in my earlier post, the clients doesn't want the code to be refractored.
Thats where the challenge has come when doing the unittesting, as they didn't use the framework properly.
Ah, my apologies, I must have missed that.
In that case you may want to check this out powermock. The exaple given shows you how to mock constructors and the example is pretty much what you need.
This isn't so much a mocking framework in itself but it adds extensions and integrates with most of the popular mocking frameworks (I used Mockito).