呼叫2个测试功能的功能的单元测试



我在Java类中具有以下代码骨架,称为" testclass.java":

public String functionA () {
    if (function B() == true) {
        String testVariable = function C();
        String test2 = testVariable +"Here a test";
    } else {
        ...
    }
}

我需要对此函数函数((应用单位测试,其中已在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());
}

当我进行测试时,我在mockTestClass.functionA()中得到了:NULL。你能帮忙吗?如何测试此功能?

您通常要模拟其他类,而不是实际测试的类。但是,对于您的示例,如果您真的想模拟调用functionB()functionC(),则需要在TestClass 上进行间谍。而不是Mockito.when(mockTestClass.functionB()).thenReturn(true),您需要doReturn(true).when(mockTestClass).functionB()(functionC()也是如此(。只有这样,您的assertEquals("PAssed!", "test Here a test", mockTestClass.functionA())才会调用实际方法functionA()并通过。

最新更新