使用Powermockito在java中测试私有方法

时间:2014-02-21 15:48:10

标签: unit-testing junit mockito

我正在使用PowerMockito和jUnit来编写单元测试用例。

public class Foo {
    private String resolveApplicationId() {
        return "testApplication";
    }
}

这是我的测试用例

@RunWith(PowerMockRunner.class)
@PrepareForTest(Foo.class)
public class test{

@Before
    public void prepareTest() {
        foo = PowerMockito.spy(new Foo());
    }
@Test
public void checkApplicationIdIsResolved() throws Exception {
    PowerMockito.doNothing().when(foo, "myPrivateMethod");
    PowerMockito.verifyPrivate(foo).invoke("myPrivateMethod");
//Assert Here the returned value
}

}

请告诉我

 1. how can I assert the value returned by the method when it is called
 2. how can I call the private method
 3. if not then what actually I verify when I write test case for private methods.

感谢。

1 个答案:

答案 0 :(得分:1)

测试私有方法与测试公共方法没有区别。如果没有外部依赖项,您甚至不需要创建和使用任何模拟。唯一的问题是从test中调用private方法。这被描述为here,或者您可以使用spring utils

所以你不需要模拟你正在测试的方法。您只需要模拟在此特定测试中未测试的其他对象。所以你的测试看起来像

@Test
public void checkApplicationIdIsResolved() throws Exception {
    // makeResolveIdAccessible();
    // if needed setup mocks for objects used in resolveApplicationId 
    assertEquals(expectedApplicationId, foo.resolveApplicationId())
}