MockMVC 如何在同一测试用例中测试异常和响应代码

2022-09-01 16:02:09

我想断言引发异常并且服务器返回500内部服务器错误。

为了突出显示意图,提供了代码片段:

thrown.expect(NestedServletException.class);
this.mockMvc.perform(post("/account")
            .contentType(MediaType.APPLICATION_JSON)
            .content(requestString))
            .andExpect(status().isInternalServerError());

当然,无论我写还是.无论语句下方是否引发异常,测试都将通过。isInternalServerErrorisOkthrow.except

您将如何解决这个问题?


答案 1

如果您有一个异常处理程序,并且想要测试特定异常,则还可以断言该实例在已解决的异常中有效。

.andExpect(result -> assertTrue(result.getResolvedException() instanceof WhateverException))

答案 2

您可以获取对 MvcResult 和可能已解决的异常的引用,并使用常规 JUnit 断言进行检查...

MvcResult result = this.mvc.perform(
        post("/api/some/endpoint")
                .contentType(TestUtil.APPLICATION_JSON_UTF8)
                .content(TestUtil.convertObjectToJsonBytes(someObject)))
        .andDo(print())
        .andExpect(status().is4xxClientError())
        .andReturn();

Optional<SomeException> someException = Optional.ofNullable((SomeException) result.getResolvedException());

someException.ifPresent( (se) -> assertThat(se, is(notNullValue())));
someException.ifPresent( (se) -> assertThat(se, is(instanceOf(SomeException.class))));