我是编写单元测试用例的新手,需要帮助。我读了一些可能的解决方案,但目前还不起作用。
Main类如下所示,它调用了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:我按照下面的方式编写了单元测试用例。
@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()方法应该返回列表)请让我知道我在这里做错了什么。提前谢谢你。我也张贴我的setSignerList()的代码,以防万一,如果你想看到它的参考。
private List<Signer> setSignerList() {
List<Signer> signerList = new ArrayList<Signer>();
signerList.add(primarySigner); // primarySigner is mock object.
return signerList;
}
您已经模拟了objSession,并且当这两个方法被测试用例调用时,您已经返回了空列表。
when(....). thenreturn(....)用于为该条件指定条件和返回值(stub)。由于您已经模拟了它并使用存根返回所需的列表,因此它不会返回实际调用返回的列表。
List<Signer> signerList = setSignerList(); // EMPTY LIST
List<Signer> additionalSignerList = setSignerList(); // EMPTY LIST
when(objSession.getSignerList()).thenReturn(signerList); //MOCK
when(nsbSession.getAdditionalSignerList()).thenReturn(additionalSignerList); // MOCK