springboot控制器测试无法处理异常

时间:2018-10-24 21:52:23

标签: exception-handling controller spring-boot-test

我是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"}

1 个答案:

答案 0 :(得分:0)

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

相关问题