Spring 引导控制器测试不处理异常



我是SpringBoot的新手,自从使用SpringMVC以来已经有一段时间了,所以我可能错过了一些明显的东西。我的测试调用控制器,控制器抛出一个非法参数异常,就像我想要的那样。但是,测试不会处理它。相反,它失败而不是像我期望的那样通过。打电话给卷曲,我确实看到了我期望的回应。

我的测试:

@Test
void throwExceptionWhenMazeIsInvalid() {
def encodedMaze = java.net.URLEncoder.encode("""#
##########
""", "UTF-8")
mvc.perform(MockMvcRequestBuilders.get("/solve?maze=${encodedMaze}").accept(MediaType.APPLICATION_JSON))
.andExpect(status().is(500))
//                .andDo(MockMvcResultHandlers.print())
.andExpect(content().string("The maze is improperly formatted."))
.andDo(print())
//                .andReturn()
}

我测试的方法:

@RestController
class MazeController {
@RequestMapping(value = "/solve", method = RequestMethod.GET, produces = "application/json")
String solve(@RequestParam("maze") String layout){
println "MazeController.solve(${layout})"
String decoded = java.net.URLDecoder.decode(layout, "UTF-8")
if (!MazeValidator.isValid(decoded)) {
throw new IllegalArgumentException("The maze is improperly formatted.")
}
String expectedMaze = """##########
#A@@.#...#
#.#@##.#.#
#.#@##.#.#
#.#@@@@#B#
#.#.##@#@#
#....#@@@#
##########
"""

JsonBuilder json = new JsonBuilder()
//        json { message decoded }
json { message expectedMaze }
println "============= RETURNING response"
return json.toString()
}
}

我的卷发:

> curl localhost:8080/solve
{"timestamp":"2018-10-24T21:45:19.025+0000","status":500,"error":"Internal Server Error","message":"The maze is improperly formatted.","path":"/solve"}

您是否尝试过用于模拟 mvc 的 setHandlerExceptionResolvers?

最新更新