【发布时间】:2018-10-24 21:52:22
【问题描述】:
我是 SpringBoot 的新手,使用 SpringMVC 已经有一段时间了,所以很可能我遗漏了一些明显的东西。我的测试调用了控制器,控制器按照我的意图抛出了 IllegalArgumentException。但是,测试不处理它。相反,它失败了,而不是像我预期的那样通过了。调用 curl,我确实看到了预期的响应。
我的测试:
@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"}
【问题讨论】:
标签: exception-handling controller spring-boot-test