具有Void返回类型

时间:2015-08-30 15:11:17

标签: java junit mocking

我是编写junit测试用例的新手,需要帮助。我读到了可能的解决方案,但他们现在还没有工作。

主类如下所示,它调用类addResponseData的方法(此方法仅在会话中设置值并且不返回任何内容)。请参阅以下代码。

@Test
public void testPublishData_Success() throws java.lang.Exception {
    when(GetPropValues.getPropValue(PublisherConstants.ATMID)).thenReturn("ATM");
    when(GetPropValues.getPropValue(PublisherConstants.DATA_SOURCE)).thenReturn("PCE");

    ReadAndWriteFiles mockFiles = Mockito.mock(ReadAndWriteFiles.class);
    PowerMockito.whenNew(ReadAndWriteFiles.class).withNoArguments().thenReturn(mockFiles);
    Mockito.when(mockFiles.getAllFiles()).thenReturn(null);

    KafkaProducer mockProducer = Mockito.mock(KafkaProducer.class);
    PowerMockito.whenNew(ReadAndWriteFiles.class).withAnyArguments().thenReturn(mockProducer);

    producer.publishData(null, "Test", "Data1");
}

    ResponseWrapper signerResponse;
    try {
        privateClassObj.ensureDataLoaded(objSession); // Loads the required data into objSession)

        signerResponse = new ResponseWrapper(ResponseType.SUCCESS);
        signerResponse.addResponseData("signerList", objSession.getSignerList());
        signerResponse.addResponseData("additionalSignerList", objSession.getAdditionalSignerList());
    }
    catch (ServiceException err) {
        signerResponse = new ResponseWrapper(ResponseType.PARTIAL_SUCCESS);
    }

    return signerResponse;
}

TestClass:我已按照以下方式编写了junit测试用例。

    @Test
public void testSuccessfulCallWithSigners() {
    List<Signer> signerList = setSignerList();
    List<Signer> additionalSignerList = setSignerList();
    when(objSession.getSignerList()).thenReturn(signerList);
    when(nsbSession.getAdditionalSignerList()).thenReturn(additionalSignerList);
    ResponseWrapper output = signerController.getUsers(request); // actual method call
    assertEquals(output, responseWrapper);
}

这个测试用例失败了,因为我总是得到空的signerList和additionalSignerList。(测试用例结果是getAdditionalSignerList()方法应该返回List)请让我知道我在这里做错了什么。提前致谢。我也发布了我的setSignerList()代码,如果你想看到它以供参考。

private List<Signer> setSignerList() {
    List<Signer> signerList = new ArrayList<Signer>();
    signerList.add(primarySigner); // primarySigner is mock object.
    return signerList;
}

1 个答案:

答案 0 :(得分:0)

你已经模拟了objSession,并且当测试用例调用这两个方法时你也返回了空列表。

when(....)。thenReturn(....)用于指定此条件的条件和返回值(Stubbing)。当你模拟它并使用存根返回所需的列表时,它将不返回实际通话返回的列表。

List<Signer> signerList = setSignerList(); // EMPTY LIST
List<Signer> additionalSignerList = setSignerList(); // EMPTY LIST
when(objSession.getSignerList()).thenReturn(signerList); //MOCK
when(nsbSession.getAdditionalSignerList()).thenReturn(additionalSignerList); // MOCK