【问题标题】:is there a way to test all 5XX or 4XX codes with Mockito?有没有办法用 Mockito 测试所有 5XX 或 4XX 代码?
【发布时间】:2021-02-05 13:58:32
【问题描述】:

大家好,我在一个依赖于另一个微服务的微服务中工作。我正在使用Restemplate 处理其余的消耗,一切正常,但我还需要获得 100% 的声纳测试覆盖率。

关于测试内容,我想涵盖 4XX 或 5XX 代码的任何可能性,以确保我的应用程序的行为。这是我的一项测试的代码:

@Test
@DisplayName("GetAfiliations: 5XX Exception")
void getAfiliationsWithError5XX() throws IOException, InternalException {

    ContainerGetExternalAfiliations containerGetExternalAfiliationscontainerGetExternalAfiliations = mapper.readValue(getClass().getClassLoader().getResourceAsStream("jsons/afiliacion.json")
            , ContainerGetExternalAfiliations.class);

    RequestGetAfiliations req = new RequestGetAfiliations();
    req.setDate(LocalDate.now());

    String requestString = mapper.writeValueAsString(req);

    this.server
            .expect(ExpectedCount.once(), requestTo(URL_GET_AFILIATION))
            .andExpect(method(HttpMethod.POST))
            .andExpect(content().contentType(MediaType.APPLICATION_JSON))
            .andExpect(content().json(requestString))
            .andRespond(withStatus(HttpStatus.BAD_GATEWAY));



    Throwable exceptionThatWasThrown = assertThrows(InternalException.class, () -> afiliationsBO.getAfiliations("UID"));
    assertTrue(exceptionThatWasThrown.getMessage().contains("Error handlig external service"));

    this.server.verify();
}

正如您在上面的测试中看到的,我只处理 502 http 错误,但如果我想测试 500,我将需要另一个测试,然后再测试 503,依此类推。

任何人都知道只在一次测试中测试每个 5XX 或 4XX 的方法吗?

非常感谢您阅读我。

【问题讨论】:

  • 一个the 100% test fallacy。这些是不同的测试,所以不要尝试为此编写 1 个测试,也不要推迟 100% 的测试覆盖率,因为 100% 的覆盖率没有意义。
  • 这听起来确实有点矫枉过正,特别是如果你只是重新抛出一个通用异常说“发生错误”。 --- 为您真正关心值的 HTTP 代码添加测试用例,您将在其中执行特定于代码/代码集的操作。 --- 但是如果你只是想重新抛出一个错误,那么就写一个测试说如果状态码不OK就会失败。使用 2-3 个不同的值来记录它涵盖任何 4XX 5XX 的事实,仅此而已。 --- 您可以使用所有可能的状态代码参数化测试,这将更具破坏性 imo。

标签: java spring-boot junit mockito resttemplate


【解决方案1】:
<...>
.andExpect(MockMvcResultMatchers.status().is5xxServerError());

【讨论】:

  • A code-only answer is not high quality。虽然此代码可能很有用,但您可以通过说明其工作原理、工作方式、何时应该使用以及它的局限性来改进它。请edit您的回答包括解释和相关文档的链接。
猜你喜欢
  • 1970-01-01
  • 2015-05-21
  • 2017-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-26
  • 2017-10-20
  • 1970-01-01
相关资源
最近更新 更多