我想断言,抛出一个异常,并且服务器返回一个500内部服务器错误。
要强调的是提供一个代码片段的意图:
thrown.expect(NestedServletException.class);
this.mockMvc.perform(post("/account")
.contentType(MediaType.APPLICATION_JSON)
.content(requestString))
.andExpect(status().isInternalServerError());
当然,如果我把它写这么想的重要isInternalServerError
或isOk
。 如果有异常抛出下面的测试将通过无关throw.except
声明。
你会如何去解决呢?
你可以试一下如下 -
创建自定义匹配
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); } }
声明一个@Rule
在JUnit类如下-
@Rule public ExpectedException exception = ExpectedException.none();
使用自定义匹配测试情况下 -
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:我提供了一个通用的伪代码,你可以定制按您的要求。
在你的控制器:
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
}