简体   繁体   English

如何使用PowerMockito在静态方法中模拟新的类实例

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

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(); 而且我在dc.methodCall()中得到了空指针异常;

Thanks 谢谢

Make sure that you have the MyClass in @PrepareForTest . 确保在@PrepareForTest具有MyClass Also, I recommend use the withParameterTypes . 另外,我建议使用withParameterTypes It's not mandatory, but it helps avoid some errors. 它不是强制性的,但有助于避免某些错误。

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. 在withArguments()方法调用中使用Powermockito.anyString()或类似的东西(我不确定版本是否正确)。 Do not use the string as such. 不要这样使用字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM