PowerMock,模拟一个静态方法,然后在所有其他静态上调用真实方法
我正在设置模拟类的静态方法。我必须在带注释的 JUnit 设置方法中执行此操作。@Before
我的目标是将类设置为调用实际方法,除了那些我显式模拟的方法。
基本上:
@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?
}
我遇到的问题是,不幸的是,在方法中会抛出一个if,并提供一个值。StaticUtilClass
public static int someStaticMethod(String s)
RuntimeException
null
因此,我不能简单地走调用真实方法作为默认答案的明显路线,如下所示:
@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);
}
我需要设置默认的 Answer,以便在模拟我感兴趣的方法的结果后调用所有其他静态方法的真实方法。
这可能吗?