13

我正在使用 MockMVC 来测试我的控制器。

我有以下控制器:

public class A{

    ...

    @RequestMapping("/get")
    public List<ADTO> get(@RequestParam(defaultValue = "15", required = false) Integer limit) throws IOException {
        if(limit <= 0 || limit >= 50){
            throw new IllegalArgumentException();
        }
        ...
        return aDTOs;
    }

}

我目前的测试看起来像这样:

@Test
public void testGetAllLimit0() throws Exception {
    mockMvc.perform(get("/A/get")
            .param("limit","0")
            )
            .andDo(print())
            .andExpect(...);
}

我正在用这个实例化 MockMVC:

@Before
public void setup() {
    this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}

如何处理控制器中抛出的异常?

后期编辑:

我不确定我的代码最近发生了什么,但它通过了测试:

@Test
public void testGetAllLimit0() throws Exception {
    mockMvc.perform(get("/A/get")
            .param("limit","0")
            )
            .andDo(print())
            .andExpect(status().is(500));
}

如果我替换为 ,它仍然会is(500)通过isOk()。这不好,我应该以某种方式检查该异常。

如果我运行 agradle build我得到这个:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalArgumentException
4

2 回答 2

7

您是否尝试使用像这里这样的自定义 ExceptionHandler ?:https ://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc

如果这样做,您可以返回自定义 HTTP 响应代码并在测试中验证它们。

于 2015-04-13T17:36:24.263 回答
3

更简单的方法是注入到您的 Spring 测试上下文中,否则它会在之前@ExceptionHandler抛出异常。MockMvc.perform().andExpect()

@ContextConfiguration(classes = { My_ExceptionHandler_AreHere.class })
@AutoConfigureMockMvc
public class Test {
    @Autowired
    private MockMvc mvc;

    @Test
    public void test() {
        RequestBuilder requestBuilder = MockMvcRequestBuilders.post("/update")
                .param("branchId", "13000")
                .param("triggerId", "1");
        MvcResult mvcResult = mvc.perform(requestBuilder)
                .andExpect(MockMvcResultMatchers.status().is4xxClientError())
                .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON_UTF8))
                .andExpect(__ -> Assert.assertThat(
                        __.getResolvedException(),
                        CoreMatchers.instanceOf(SecurityException.class)))
                .andReturn();
}

那种方式是MvcResult.getResolvedException()例外@Controller

于 2020-07-15T08:14:24.403 回答