问题
I have a class with static method, inside the static method I creating an instance of a different class and save it inside a map. I need to write unit tests for this method. What is the best way to do it?
For example:
public class MyClass {
public static synchronized void method (String str1, String str2, Object obj){
do something.....
DifferentClass dc = new DifferentClass(str1,str2,obj);
dc.methodCall();
do something.....
}
}
Tried to do it with:
DifferentClass dc = PowerMockito.mock(DifferentClass.class);
PowerMockito.whenNew(DifferentClass.class).withArguments(str1,str2,obj).thenReturn(dc);
And I am getting null pointer exception in dc.methodCall();
Thanks
回答1:
Make sure that you have the MyClass
in @PrepareForTest
.
Also, I recommend use the withParameterTypes
. It's not mandatory, but it helps avoid some errors.
回答2:
The mocking might not be working. Use Powermockito.anyString() or something like that (I'm not sure of the correct version) inside the withArguments() method call. Do not use the string as such.
来源:https://stackoverflow.com/questions/36019176/how-to-use-powermockito-to-mock-new-class-instance-inside-a-static-method