【问题标题】:springboot controller test does not handle exceptionspring boot 控制器测试不处理异常
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-13
      • 1970-01-01
      • 2018-11-19
      • 1970-01-01
      • 2013-08-11
      • 2019-10-09
      • 2022-11-29
      • 2023-03-28
      相关资源
      最近更新 更多