How to use PowerMockito to mock new class instance inside a static method

此生再无相见时 提交于 2019-12-11 10:17:19

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!