Java 如何编写Mockito测试用例?
嗨,我在为你写一个测试用例Java 如何编写Mockito测试用例?,java,unit-testing,testing,mockito,Java,Unit Testing,Testing,Mockito,嗨,我在为你写一个测试用例 @Override public SnapDocument updateFlights(SnapDocument snapDocument, FlightListingResponse flightsResponse) { HashMap<String, FaresInfo> outboundFlights = new HashMap<>(); HashMap<String, Fare
@Override
public SnapDocument updateFlights(SnapDocument snapDocument, FlightListingResponse flightsResponse) {
HashMap<String, FaresInfo> outboundFlights = new HashMap<>();
HashMap<String, FaresInfo> inboundFlights = new HashMap<>();
Objects.requireNonNull(flightsResponse.getOutboundFlights()).getFlights().forEach(faresInfo -> outboundFlights.put(faresInfo.getJourneySellKey(), faresInfo));
Objects.requireNonNull(flightsResponse.getReturnFlights()).getFlights().forEach(faresInfo -> inboundFlights.put(faresInfo.getJourneySellKey(), faresInfo));
snapDocument.setOutboundFlights(outboundFlights);
snapDocument.setInboundFlights(inboundFlights);
return snapDocument;
}
构建失败了,如何为此编写测试用例以便提高代码的覆盖率?
当
时,给定
和验证
只应在处理模拟时使用。
由于您的代码使用普通的旧java对象,并且没有调用其他外部组件,因此您不需要它们
只需构造要传递给方法的pojo,并断言返回的pojo包含正确的值。您不需要mockito,因为测试不需要mock
@测试
void testUpdateFlights(){
//安排
SnapService SnapService=新的SnapServiceImpl();
SnapDocument sd=新的SnapDocument();
FlightListingResponse响应=新建FlightListingResponse();
答复:setOutboundFlights(…);
回复:setReturnFlights(…);
//表演
SnapDocument结果=snapService.updateFlights(sd,响应);
//断言
资产(result.getOutboundFlights())。包含(…);
}
您现在不需要它们,但什么时候需要模拟?如果您的代码调用了一个未被测试的组件,并且您不希望执行它的实际实现。单元测试是测试一个工作单元。所有其他外部组件都应该模拟出来。不清楚你在问什么。这里根本没有测试该方法中的任何内容——您没有验证
updateFlights
使用的任何方法是否已被调用等。但是,请注意,如果您正在测试updateFlights
,您可能希望测试生成的snapDocument
而不是updateFlights
的内部实现,但是测试的容易程度可能决定了updateFlights
最终如何被测试。
public void updateFilghtsSuccess(){
when(snapService.getSnapDocument(any())).thenReturn(snapDocument);
when(snapService.updateFlights(snapDocument, flightListingResponse)).thenReturn(snapDocument);
verify(snapService).updateFlights(snapDocument, flightListingResponse);
}