我想Assert引发了一个异常,并且服务器返回一个500内部服务器错误。
为了突出显示意图,提供了一个代码片段:
thrown.expect(NestedServletException.class);
this.mockMvc.perform(post("/account")
.contentType(MediaType.APPLICATION_JSON)
.content(requestString))
.andExpect(status().isInternalServerError());
当然,写isInternalServerError
还是isOk
并不重要,不管throw.except
语句下面是否抛出异常,测试都会通过。
你打算怎么解决这个问题?
5条答案
按热度按时间ego6inou1#
如果您有一个异常处理程序,并且想要测试特定的异常,您还可以Assert该示例在已解决的异常中是有效的。
UPDATE(gavenkoa)不要忘记将带注解的
@ExceptionHandler
方法注入测试上下文,否则异常将在.perform()
发生,而不是使用.andExpect()
捕获它,基本上注册:用
@Import(value=...)
或@ContextConfiguration(classes=...)
或通过其它方式来实现。ef1yzkbh2#
您可以获得对MvcResult的引用和可能已解决的异常,并使用常规JUnitAssert进行检查...
qzlgjiam3#
您可以尝试以下方法-
1.创建自定义匹配器
1.在JUnit类中声明一个
@Rule
,如下所示-1.在测试用例中使用自定义匹配器作为-
**P.S.:**我提供了一个通用的伪代码,您可以根据您的要求进行定制。
klh5stk14#
我最近遇到了同样的错误,我没有使用MockMVC,而是创建了如下集成测试:
和
这篇文章很有帮助:https://github.com/spring-projects/spring-boot/issues/7321
chy5wohz5#
在控制器中:
在您的测试中: