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

Unit testing 使用Powermockito在java中测试私有方法,unit-testing,junit,mockito,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

我正在使用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.

谢谢。

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

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

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

你读过这篇文章吗?没有,但我读过这篇文章。然而,这篇文章并没有回答我的问题。对于使用PowerMockito为私有方法编写JUnit更为详细。