【发布时间】:2013-02-01 16:49:53
【问题描述】:
我正在设置模拟类的静态方法。我必须在 @Before-annotated JUnit 设置方法中执行此操作。
我的目标是设置类来调用真正的方法,除了那些我明确模拟的方法。
基本上:
@Before
public void setupStaticUtil() {
PowerMockito.mockStatic(StaticUtilClass.class);
// mock out certain methods...
when(StaticUtilClass.someStaticMethod(anyString())).thenReturn(5);
// Now have all OTHER methods call the real implementation??? How do I do this?
}
我遇到的问题是,在StaticUtilClass 中,如果提供null 值,public static int someStaticMethod(String s) 方法不幸会抛出RuntimeException。
所以我不能简单地将调用真实方法作为默认答案的明显路线如下:
@Before
public void setupStaticUtil() {
PowerMockito.mockStatic(StaticUtilClass.class, CALLS_REAL_METHODS); // Default to calling real static methods
// The below call to someStaticMethod() will throw a RuntimeException, as the arg is null!
// Even though I don't actually want to call the method, I just want to setup a mock result
when(StaticUtilClass.someStaticMethod(antString())).thenReturn(5);
}
我需要设置默认答案以在所有其他静态方法上调用真实方法之后我模拟了我有兴趣模拟的方法的结果。
这可能吗?
【问题讨论】:
-
匹配器应该是 anyString() 而不是 antString()
-
@Nathan Adams - 是的。已更新。
标签: java junit mockito powermock