PowerMockito私有void方法问题

时间:2016-12-14 08:45:35

标签: java junit mocking powermock

我有以下课程

class PowerMockitoTest{

  private void TestPrivateMethod(){
    System.out.println("Inside private method");
  }

  public void TestPublicMethod(){
    System.out.println("Inside public method");
    TestPrivateMethod();
  }
}

我已经创建了Test类,如下所示

@RunWith(PowerMockRunner.class)
public class PowerMockitoExampleTest {

@Test
public void test() throws Exception {

 PowerMockitoTest testclass = PowerMockito.spy(new PowerMockitoTest());
 PowerMockito.doNothing().when(testclass,"TestPrivateMethod");
 testclass.TestPublicMethod();

}

}

而不是将OP作为公共方法'我变得非常奇怪OP作为'内部私人方法'。虽然我已经使用私有方法来执行任何操作但它的调用以及公共方法的sysout都没有被打印出来。

当我使用PowerMockito.doAnswer()时它工作正常,但它需要方法在包级别而不是私有。

2 个答案:

答案 0 :(得分:1)

这样写:

    PowerMockitoTest testclass = PowerMockito.spy(new PowerMockitoTest());
    try {
        PowerMockito.doNothing().when(testclass,  PowerMockito.method(PowerMockitoTest.class, "TestPrivateMethod")).withNoArguments();
    } catch (Exception e) {
        e.printStackTrace();
    }
    testclass.TestPublicMethod();

顺便说一句: 测试是关于模拟输入和调查输出(它可以是模块的状态,函数的结果或对其他函数的调用)。

你不应该模仿私人方法,因为它们的结果不应被视为输入因为它们从外面看不到。

答案 1 :(得分:0)

我认为代码中缺少的部分是@PrepareForTest部分。您必须在@RunWith批注之后使用@PrepareForTest添加类名称

@RunWith(PowerMockRunner.class)
@PrepareForTest({Class1.class, Class2.class})
public class ClassTest
相关问题