Can we mock 2nd object creation using powermock - java

We can mock the object creation using powermock using below line:
MyClass myObj = getMyObj();
PowerMockito.whenNew(MyClass.class).withAnyArguments().thenReturn(myObj);
Now in my class where I am writing test case, I have logic of this kind:
public class TestClass {
public void testMethod() {
MyClass obj = new MyClass();
boolean flag = doSomeOperation();
if(flag) {
MyClass obj1 = new MyClass();
//doSomeOtherOp();
}
}
}
Here I want to mock the second object creation obj1, is it possible with powermock to control which object I want to mock. Here I don't want to mock the 1st object obj.

I thought this to be simple:
PowerMockito.whenNew(MyClass.class).withAnyArguments().thenReturn(firstResult)
.thenReturn(anotherResult);
but unfortunately, although chaining is possible in other contexts, it seems that PowerMockito doesn't allow for it.
( Something like
when(someMock.toString()).thenReturn("a").thenReturn("b");
System.out.println(someMock.toString() +factory.toString();
just nicely prints ab ! )
So the only answer I can give right now: you wrote hard to test code. Consider not doing that.
Instead of relying on PowerMock to mock calls to new() you should rather step back and change your design. For example by using a factory in your production code. So instead of calling new() directly, you simply ask the factory for new instances. And that factory can be easily mocked without the need of PowerMock(ito).

Related

How to proceed to test a function that receives a "Class" parameter using jMockIt?

I'm developing a function that uses reflection on a Class<?> object that is passed as parameter and returns a POJO with some fields populated, something like this:
public MyPojo functionDeveloper(Class<?> targetClass) { /*...*/ }
This function works fine and does what it needs to do, so no problems on this side.
Now, I need to create a unit test for this function, but I can't really figure out how to proceed here: We are supposed to mock as much as we can (which basically rules out creating a dummy parameter), with some random parameter from a generic class I would go like this:
#Tested
TestedClass testedClassInstance;
#Mocked
private MyGenericClass myGenericClass;
#Mocked
private Field[] fields;
#Test
public void testFunction() {
new Expectations(testedClassInstance) {
myGenericClass.getDeclaredFields();
result = fields;
}
/* assertions here*/
}
...and my intention with the Class<?> parameter was the same: being able to tell "when the code says "targetClass.getDeclaredFields()", then return the mocked object "field" I declared before, but jMockIt is complaining about not being able to mock the Class<?> object.
So, how do I proceed here? I get that java.lang.Class is "special" and all that, and there's probably something I'm missing from how jMockIt works. Any idea?
When you use Mocked on a class, you holds a mocked instance automatically created by jmockit lib.
So, try myGenericClass.getClass().getDeclaredFields()
More details : https://jmockit.github.io/tutorial/Mocking.html#mocked
You have a really simple case of a function. Functions are incredibly easy to test and rarely need mocks. They receive some input and return some output. What you need to do, is to test that some input produced some output.
#Tested
TestedClass testedClassInstance;
#Test
public void egReturnsAllFieldsOfTheProvidedClass() {
MyPojo result = testedClassInstance.functionDeveloper(MyGenericClass.class)
/* assertions here*/
}

How can I create fake data and the data object for unit testing?

I have a class that implements a cache and I want to write a JUnit test for it.
The class implements and interface with methods like:
public void insert(Object key, Object value);
public Object getFromCache(Object key);
and the basic implementation is a singleton.
I am writing a JUnit test but I don't know how to properly create a dummy cache with data in order to use for testing.
Right now I am doing:
#Test
public void myTest() {
MyCache cache = MyCache.getInstance();
populateWithData(cache);
//test cache
asserEquals etc
}
How can I avoid using the getInstance() and not populate on each test?
Apparently I slightly misread your question.
As the other two answers state, if you want to have a specific cache which you can read from when running each testcase, you could use a ´#before´ method, which initializes your object to be used in your testcase. Each ´#before´ method defined is called prior to calling each testcase. This means that you can write the code to instantiate the object once instead of many times.
Note that if you want to do something different in a testcase, consider adding the customization at the top of that, instead of edition your #before method, since that will impact all your testcases.
Just for clarity's sake, I will include some code:
MyCache cache = null;
#before
public void initCache(){
cache = MyCache.getInstance();
populateWithData(cache);
}
// ... rest of your program here ...
Original answer:
You can use this if you want to do more fancy testing of more complicated objects. This can still be used in conjunction with the ´#before´ annotation
You could try mockito...
This is basically a framework to mock off a function or class, that you are not interested in implementing in its totally, especially for testing.
Here is a sample using a mocked off list:
import static org.mockito.Mockito.*;
// mock creation
List mockedList = mock(List.class);
// using mock object - it does not throw any "unexpected interaction" exception
mockedList.add("one");
mockedList.clear();
// selective, explicit, highly readable verification
verify(mockedList).add("one");
verify(mockedList).clear();
// you can mock concrete classes, not only interfaces
LinkedList mockedList = mock(LinkedList.class);
// stubbing appears before the actual execution
when(mockedList.get(0)).thenReturn("first");
// the following prints "first"
System.out.println(mockedList.get(0));
// the following prints "null" because get(999) was not stubbed
System.out.println(mockedList.get(999));
You can basically tell mockito which functions you expect to call on the object, and what you expect the result to be... very versatile. I expect that it will fulfill your needs.
'Reset' singleton before each test. More details can be found here.
For example:
#Before
public void resetMyCacheSingleton() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
Field instance = MyCache.class.getDeclaredField("instance");
instance.setAccessible(true);
instance.set(null, null);
}
You can use #BeforeClass annotation to do something which will be common and may be computational expensive stuff.
This will ran only once before all the testcases.
#BeforeClass
public static void myTest() {
MyCache cache = MyCache.getInstance();
populateWithData(cache);
//test cache
asserEquals etc
}
P.S. Since #BeforeClass can be used with static method only, populateWithData() needs to be static as well. and since populateWithData() method is static, variables used inside it must be static as well.
You can also check #AfterClass to clean/reset some data/resources.

Unit test fails because the service is offline

I have a unit test that fails because it indirectly calls a method which is dependent upon a service. But when unit tests are run, the service is offline. I tried using Mockito for mocking the behavior of this service dependent method, but the problem is that this method is a static method in a final class, so Mockito does not work in this case.
I also tried using PowerMock with Mockito, but again as the method is not called directly from the unit test, it does not work. This is the skeleton of my unit test:
#RunWith(PowerMockRunner.class)
#PrepareForTest(FinalClassWithStaticMethod.class)
public class MyObjTestCase {
#Test public void myRandomTest() throws Exception {
PowerMockito.mockStatic(FinalClassWithStaticMethod.class);
MyObj returnObj = new MyObj();
// setup fields for returnObj
...
...
PowerMockito.when(FinalClassWithStaticMethod.staticMethod((AnotherObj)anyObject())).thenReturn(returnObj);
AnotherObj obj = new AnotherObj();
// setup fields for obj...
MyObj mockedObj = FinalClassWithStaticMethod.staticMethod(obj); // This returns the mocked value.
// TestUtil.staticMethod calls another class' method which calls FinalClassWithStaticMethod.staticMethod.
MyObj myObj = TestUtil.staticMethod(obj); // This does not return mocked value.
}
}
My questions:
Are the unit tests even meant for such scenarios?
Is there a way by which I can get this unit test to work without modifying the final class? In case I do have to modify the existing classes, what is the correct way of doing it by minimal effects on the dependent code? Although it is a specific scenario, links to examples that exhibit such refactoring will be great help.
In your case, you should ideally be mocking the service object. The mocking will only work if the method that is calling the service is using the mocked object. If the client for the service can be created and passed to the class calling the service directly from the unit test (setter/constructor) when the object is created in the unit test, then you don't have to make too many changes.
Sample code:
class CallsService {
public CallsService(final ServiceClient client) {
... }
public someMethod() {
client.callService();
}
}
In unit test:
void test() {
ServiceClient mockedClient = mock(ServiceClient.class);
// Setup mocks to return as required
CallsService caller = new CallsService(mockedClient);
}
This way the caller will use the mockedClient in the unit test, and in the actual program it can get a client to the real service.

Need advice on unit testing with suppressing submethods and constructors

I have some weird code like this
B param = ...;
D main(){
return A.method(param, C.class, new String[]{"abc"}, new SomeClass()).get();
}
where
public static A method(...)
public D get()
How can I mock method main() to suppress submethods invocations and suppress constructing of objects?
I need to mock result of get()
Aside from a better designed method that injects instances into the method instead of create them, you can use Powermock to mock constructor calls so the calls to new will actually create mock objects.
here is powermock's tutorial on mock constructors with mockitto
http://code.google.com/p/powermock/wiki/MockitoUsage13
IN your test you will be able to say:
SomeClass myMock = mock(SomeClass.class);
whenNew(SomeClass.class).withNoArguments().thenReturn(myMock)

Mockito: Trying to spy on method is calling the original method

I'm using Mockito 1.9.0. I want mock the behaviour for a single method of a class in a JUnit test, so I have
final MyClass myClassSpy = Mockito.spy(myInstance);
Mockito.when(myClassSpy.method1()).thenReturn(myResults);
The problem is, in the second line, myClassSpy.method1() is actually getting called, resulting in an exception. The only reason I'm using mocks is so that later, whenever myClassSpy.method1() is called, the real method won't be called and the myResults object will be returned.
MyClass is an interface and myInstance is an implementation of that, if that matters.
What do I need to do to correct this spying behaviour?
Let me quote the official documentation:
Important gotcha on spying real objects!
Sometimes it's impossible to use when(Object) for stubbing spies. Example:
List list = new LinkedList();
List spy = spy(list);
// Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)
when(spy.get(0)).thenReturn("foo");
// You have to use doReturn() for stubbing
doReturn("foo").when(spy).get(0);
In your case it goes something like:
doReturn(resultsIWant).when(myClassSpy).method1();
In my case, using Mockito 2.0, I had to change all the any() parameters to nullable() in order to stub the real call.
My case was different from the accepted answer. I was trying to mock a package-private method for an instance that did not live in that package
package common;
public class Animal {
void packageProtected();
}
package instances;
class Dog extends Animal { }
and the test classes
package common;
public abstract class AnimalTest<T extends Animal> {
#Before
setup(){
doNothing().when(getInstance()).packageProtected();
}
abstract T getInstance();
}
package instances;
class DogTest extends AnimalTest<Dog> {
Dog getInstance(){
return spy(new Dog());
}
#Test
public void myTest(){}
}
The compilation is correct, but when it tries to setup the test, it invokes the real method instead.
Declaring the method protected or public fixes the issue, tho it's not a clean solution.
The answer by Tomasz Nurkiewicz appears not to tell the whole story!
NB Mockito version: 1.10.19.
I am very much a Mockito newb, so can't explain the following behaviour: if there's an expert out there who can improve this answer, please feel free.
The method in question here, getContentStringValue, is NOT final and NOT static.
This line does call the original method getContentStringValue:
doReturn( "dummy" ).when( im ).getContentStringValue( anyInt(), isA( ScoreDoc.class ));
This line does not call the original method getContentStringValue:
doReturn( "dummy" ).when( im ).getContentStringValue( anyInt(), any( ScoreDoc.class ));
For reasons which I can't answer, using isA() causes the intended (?) "do not call method" behaviour of doReturn to fail.
Let's look at the method signatures involved here: they are both static methods of Matchers. Both are said by the Javadoc to return null, which is a little difficult to get your head around in itself. Presumably the Class object passed as the parameter is examined but the result either never calculated or discarded. Given that null can stand for any class and that you are hoping for the mocked method not to be called, couldn't the signatures of isA( ... ) and any( ... ) just return null rather than a generic parameter* <T>?
Anyway:
public static <T> T isA(java.lang.Class<T> clazz)
public static <T> T any(java.lang.Class<T> clazz)
The API documentation does not give any clue about this. It also seems to say the need for such "do not call method" behaviour is "very rare". Personally I use this technique all the time: typically I find that mocking involves a few lines which "set the scene" ... followed by calling a method which then "plays out" the scene in the mock context which you have staged... and while you are setting up the scenery and the props the last thing you want is for the actors to enter stage left and start acting their hearts out...
But this is way beyond my pay grade... I invite explanations from any passing Mockito high priests...
* is "generic parameter" the right term?
One more possible scenario which may causing issues with spies is when you're testing spring beans (with spring test framework) or some other framework that is proxing your objects during test.
Example
#Autowired
private MonitoringDocumentsRepository repository
void test(){
repository = Mockito.spy(repository)
Mockito.doReturn(docs1, docs2)
.when(repository).findMonitoringDocuments(Mockito.nullable(MonitoringDocumentSearchRequest.class));
}
In above code both Spring and Mockito will try to proxy your MonitoringDocumentsRepository object, but Spring will be first, which will cause real call of findMonitoringDocuments method. If we debug our code just after putting a spy on repository object it will look like this inside debugger:
repository = MonitoringDocumentsRepository$$EnhancerBySpringCGLIB$$MockitoMock$
#SpyBean to the rescue
If instead #Autowired annotation we use #SpyBean annotation, we will solve above problem, the SpyBean annotation will also inject repository object but it will be firstly proxied by Mockito and will look like this inside debugger
repository = MonitoringDocumentsRepository$$MockitoMock$$EnhancerBySpringCGLIB$
and here is the code:
#SpyBean
private MonitoringDocumentsRepository repository
void test(){
Mockito.doReturn(docs1, docs2)
.when(repository).findMonitoringDocuments(Mockito.nullable(MonitoringDocumentSearchRequest.class));
}
Important gotcha on spying real objects
When stubbing a method using spies , please use doReturn() family of methods.
when(Object) would result in calling the actual method that can throw exceptions.
List spy = spy(new LinkedList());
//Incorrect , spy.get() will throw IndexOutOfBoundsException
when(spy.get(0)).thenReturn("foo");
//You have to use doReturn() for stubbing
doReturn("foo").when(spy).get(0);
I've found yet another reason for spy to call the original method.
Someone had the idea to mock a final class, and found about MockMaker:
As this works differently to our current mechanism and this one has different limitations and as we want to gather experience and user feedback, this feature had to be explicitly activated to be available ; it can be done via the mockito extension mechanism by creating the file src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker containing a single line: mock-maker-inline
Source: https://github.com/mockito/mockito/wiki/What%27s-new-in-Mockito-2#mock-the-unmockable-opt-in-mocking-of-final-classesmethods
After I merged and brought that file to my machine, my tests failed.
I just had to remove the line (or the file), and spy() worked.
One way to make sure a method from a class is not called is to override the method with a dummy.
WebFormCreatorActivity activity = spy(new WebFormCreatorActivity(clientFactory) {//spy(new WebFormCreatorActivity(clientFactory));
#Override
public void select(TreeItem i) {
log.debug("SELECT");
};
});
As mentioned in some of the comments, my method was "static" (though being called on by an instance of the class)
public class A {
static void myMethod() {...}
}
A instance = spy(new A());
verify(instance).myMethod(); // still calls the original method because it's static
Work around was make an instance method or upgrade Mockito to a newer version with some config: https://stackoverflow.com/a/62860455/32453
Bit late to the party but above solutions did not work for me , so sharing my 0.02$
Mokcito version: 1.10.19
MyClass.java
private int handleAction(List<String> argList, String action)
Test.java
MyClass spy = PowerMockito.spy(new MyClass());
Following did NOT work for me (actual method was being called):
1.
doReturn(0).when(spy , "handleAction", ListUtils.EMPTY_LIST, new String());
2.
doReturn(0).when(spy , "handleAction", any(), anyString());
3.
doReturn(0).when(spy , "handleAction", null, null);
Following WORKED:
doReturn(0).when(spy , "handleAction", any(List.class), anyString());

Categories

Resources