MockMVC如何在同一测试用例中测试异常和响应代码 [英] MockMVC how to test exception and response code in the same test case
问题描述
我想断言引发了异常,并且服务器返回了500个内部服务器错误.
I want to assert that an exception is raised and that the server returns an 500 internal server error.
要突出显示意图,提供了一个代码段:
To highlight the intent a code snippet is provided:
thrown.expect(NestedServletException.class);
this.mockMvc.perform(post("/account")
.contentType(MediaType.APPLICATION_JSON)
.content(requestString))
.andExpect(status().isInternalServerError());
当然我写isInternalServerError
或isOk
都没关系.
不管是否在throw.except
语句下面引发异常,测试都会通过.
Of course it dosen't matter if I write isInternalServerError
or isOk
.
The test will pass regardless if an exception is thrown below the throw.except
statement.
您将如何解决这个问题?
How would you go about to solve this?
推荐答案
您可以尝试以下操作-
-
创建自定义匹配器
Create a custom matcher
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);
}
}
在JUnit类中声明一个@Rule
,如下所示-
Declare a @Rule
in JUnit class as below -
@Rule
public ExpectedException exception = ExpectedException.none();
在测试用例中将自定义匹配器用作-
Use the Custom matcher in test case as -
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());
附言::我提供了通用伪代码,您可以根据自己的要求进行自定义.
P.S.: I have provided a generic pseudo code which you can customize as per your requirement.
这篇关于MockMVC如何在同一测试用例中测试异常和响应代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!