MockMVC如何测试异常,并响应代码在同一个测试案例(MockMVC how to test ex

2019-09-04 00:18发布

我想断言,抛出一个异常,并且服务器返回一个500内部服务器错误。

要强调的是提供一个代码片段的意图:

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

当然,如果我把它写这么想的重要isInternalServerErrorisOk 。 如果有异常抛出下面的测试将通过无关throw.except声明。

你会如何去解决呢?

Answer 1:

你可以试一下如下 -

  1. 创建自定义匹配

     public class CustomExceptionMatcher extends TypeSafeMatcher<CustomException> { private String actual; private String expected; private CustomExceptionMatcher (String expected) { this.expected = expected; } public static CustomExceptionMatcher assertSomeThing(String expected) { return new CustomExceptionMatcher (expected); } @Override protected boolean matchesSafely(CustomException exception) { actual = exception.getSomeInformation(); return actual.equals(expected); } @Override public void describeTo(Description desc) { desc.appendText("Actual =").appendValue(actual) .appendText(" Expected =").appendValue( expected); } } 
  2. 声明一个@Rule在JUnit类如下-

     @Rule public ExpectedException exception = ExpectedException.none(); 
  3. 使用自定义匹配测试情况下 -

     exception.expect(CustomException.class); exception.expect(CustomException .assertSomeThing("Some assertion text")); this.mockMvc.perform(post("/account") .contentType(MediaType.APPLICATION_JSON) .content(requestString)) .andExpect(status().isInternalServerError()); 

PS:我提供了一个通用的伪代码,你可以定制按您的要求。



Answer 2:

在你的控制器:

throw new Exception("Athlete with same username already exists...");

在您的测试:

    try {
        mockMvc.perform(post("/api/athlete").contentType(contentType).
                content(TestUtil.convertObjectToJsonBytes(wAthleteFTP)))
                .andExpect(status().isInternalServerError())
                .andExpect(content().string("Athlete with same username already exists..."))
                .andDo(print());
    } catch (Exception e){
        //sink it
    }


文章来源: MockMVC how to test exception and response code in the same test case