在一个名为“TestClass.Java”的JAVA类中,我有以下代码框架:
public String functionA () {
    if (function B() == true) {
        String testVariable = function C();
        String test2 = testVariable +"Here a test";
    } else {
        ...
    }
}我需要为这个函数functionA()应用单元测试,其中已经在functionB()和functionC()上应用了测试:下面是这样做的:
private TestClass mockTestClass ;
@Test
public void testFunctionA() {
    mockTestClass = Mockito.mock(TestClass.class);
    private MockComponentWorker mockito;
    Mockito.when(mockTestClass.functionB()).thenReturn(true);//already test is done;
    Mockito.when(mockTestClass.functionC()).thenReturn("test"); //already test is done;
    mockito = mockitoContainer.getMockWorker();                 
    mockito.addMock(TestClass.class,mockTestClass);
    mockito.init();
    assertEquals("PAssed!", "test Here a test", mockTestClass.functionA());
}当我运行我的测试,我得到:NULL in mockTestClass.functionA()。你能帮忙吗?如何测试此功能?
发布于 2017-05-01 20:06:55
您通常希望模拟其他类,而不是实际测试的类。但就您的示例而言,如果您真的想模拟调用functionB()和functionC(),则需要对TestClass进行间谍。而不是Mockito.when(mockTestClass.functionB()).thenReturn(true),您需要doReturn(true).when(mockTestClass).functionB() (functionC()也是如此)。只有这样,assertEquals("PAssed!", "test Here a test", mockTestClass.functionA())才会调用实际的方法functionA()并传递。
https://stackoverflow.com/questions/43722059
复制相似问题