1

我想测试ClassToTest该类的方法methodToTest。但是我无法使它成为anotherMethod被调用的私有方法与单例类使用其公共方法methodToTest返回的值有一些依赖关系。SingletonClassgetName

我尝试使用 powermock 的 privateMethod 模拟和静态方法模拟等等,但没有帮助。
有没有人有这种情况的解决方案?

Class ClassToTest{
    public void methodToTest(){
        ...
        anotherMethod();
        ...
    }

    private void anotherMethod(){
        SingletonClass singletonObj = SingletonClass.getInstance();
        String name = singletonObj.getName();
        ...
    }
}
4

2 回答 2

0

使用mockStatic(见http://code.google.com/p/powermock/wiki/MockitoUsage13#Mocking_Static_Method

@RunWith(PowerMockRunner.class)
@PrepareForTest({SingletonClass.class})
public class ClassToTestTest {
    @Test
    public void testMethodToTest() {
        SingletonClass mockInstance = PowerMockito.mock(SingletonClass.class);
        PowerMockito.mockStatic(SingletonClass.class);
        PowerMockito.when(SingletonClass.getInstance()).thenReturn(mockInstance);
        PowerMockito.when(mockInstance.getName()).thenReturn("MOCK NAME");

        //...
    }
}
于 2013-01-25T18:12:27.203 回答
0

You should be able to use a partial mock to deal with this situation. It sounds like you want to create an instance of the object, but you just want to see if the object calls the anotherMethod() method without actually doing any of the logic in the other method. If I'm understanding correctly, the following should accomplish your goal.

@RunWith(PowerMockRunner.class)
@PrepareForTest({ClassToTest.class})
public class ClassToTestTest {
    @Test
    public void testMethodToTest() {
        ClassToTest mockInstance = 
                   PowerMock.createPartialMock(SingletonClass.class,"anotherMethod");
        PowerMock.expectPrivate(mockInstance, "anotherMethod");
        PowerMock.replay(mockInstance);
        mockInstance.methodToTest();
        PowerMock.verify(mockInstance);
    }
}
于 2013-04-16T16:29:17.507 回答