PowerMock,模拟静态方法,然后在所有其他静态上调用实际方法

Tom*_*sky 35 java junit mockito powermock

我正在设置一个类的静态方法.我必须在@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?
}
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是,在StaticUtilClass方法中,public static int someStaticMethod(String s)不幸的是抛出一个RuntimeExceptionif 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); 
}
Run Code Online (Sandbox Code Playgroud)

模拟我感兴趣的方法的结果后,我需要设置默认的Answer来调用所有其他静态方法的真实方法.

这可能吗?

zib*_*ibi 58

你在寻找什么被称为部分嘲笑.

在PowerMock中,您可以使用mockStaticPartial方法.

在PowerMockito中,您可以使用stubbing,它将仅存根定义的方法并保留其他不变的:

PowerMockito.stub(PowerMockito.method(StaticUtilClass.class, "someStaticMethod")).toReturn(5);
Run Code Online (Sandbox Code Playgroud)

也别忘了

@PrepareForTest(StaticUtilClass.class)
Run Code Online (Sandbox Code Playgroud)

  • 嗨!你能帮忙吗?如何使用特定参数的stub方法? (3认同)