本文介绍了如何使用PowerMockito在静态方法中模拟新的类实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个带有静态方法的类,在静态方法内部,我创建了另一个类的实例,并将其保存在地图中。我需要为此方法编写单元测试。最好的方法是什么?
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?
例如:
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..... } }试图做到这一点:
DifferentClass dc = PowerMockito.mock(DifferentClass.class); PowerMockito.whenNew(DifferentClass.class).withArguments(str1,str2,obj).thenReturn(dc);我在 dc.methodCall()中得到空指针异常;
And I am getting null pointer exception in dc.methodCall();
谢谢
推荐答案请确保您拥有 @PrepareForTest 中的MyClass 。 另外,我建议使用 withParameterTypes 。这不是强制性的,但有助于避免某些错误。
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.
更多推荐
如何使用PowerMockito在静态方法中模拟新的类实例
发布评论