IMLC.ME

powermock 如何 mock 私有静态方法

单元测试必需被 @RunWith(PowerMockRunner.class) 标记,同时需要使用 @PrepareForTest() 指定需要 mock 的静态类。 然后,通过 .when(Main.class, "getMessage") 方法指定需要 mock 的私有方法,也就是例子中的 Main.getMessage()

@RunWith(PowerMockRunner.class)
@PrepareForTest(Main.class)
public class MainTest {

   @Test
   public void testMethod() throws Exception {
      PowerMockito.spy(Main.class);
      PowerMockito.doReturn("Hello, world!").when(Main.class, "getMessage");
      assertEquals("Hello, world!", Main.getMessage());
   }
}