【问题标题】:How do I write a Mockito test case?如何编写 Mockito 测试用例?
【发布时间】:2021-05-05 14:39:54
【问题描述】:

你好,我正在写一个测试用例

    @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;

    }

这是我写的测试用例

    public void updateFilghtsSuccess(){
            when(snapService.getSnapDocument(any())).thenReturn(snapDocument);
            when(snapService.updateFlights(snapDocument, flightListingResponse)).thenReturn(snapDocument);
            verify(snapService).updateFlights(snapDocument, flightListingResponse);
        }

构建失败,如何为此编写测试用例以提高代码的覆盖率?

【问题讨论】:

  • 不清楚你在问什么。这里根本没有测试该方法中的任何内容-您没有验证updateFlights 使用的任何方法是否已被调用等。但是请注意,如果您正在测试updateFlights,您可能想要测试结果@ 987654325@ 而不是 updateFlights 的内部实现,但是 that 测试的难易程度可能决定了 updateFlights 最终如何被测试。

标签: java unit-testing testing mockito


【解决方案1】:

whengivenverify 只能在处理模拟时使用。 由于您的代码适用于普通的旧 java 对象并且没有调用其他外部组件,因此您不需要它们。

只需构造要传递给方法的 pojo,并断言返回的 pojo 包含正确的值。你不需要 mockito,因为测试不需要 mock。

@Test
void testUpdateFlights() {
    // Arrange
    SnapService snapService = new SnapServiceImpl();
    SnapDocument sd = new SnapDocument();
    FlightListingResponse response = new FlightListingResponse();
    response.setOutboundFlights(...);
    response.setReturnFlights(...);

    // Act
    SnapDocument result = snapService.updateFlights(sd, response);

    // Assert
    assertThat(result.getOutboundFlights()).contains(...);
}

您现在不需要它们,但什么时候需要模拟?如果您的代码调用了未在测试中的组件,并且您不希望执行它的实际实现。单元测试是测试 1 个工作单元。应模拟所有其他外部组件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-05
    • 2017-09-06
    • 1970-01-01
    • 2019-06-21
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    相关资源
    最近更新 更多