我正在设置模拟一个类的静态方法。我必须在一个用@Before
注释的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);
}
我需要将默认答案设置为在模拟我想要模拟的方法的结果之后对所有其他静态方法调用实际方法。
这个可能吗?