本文介绍了如何为独立的 MockMvc 启用控制器参数验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

控制器

@RestController
@Validated
class MyController {

    @GetMapping("/foo")
    public String unwrapped(@Min(1) @RequestParam("param") int param) {
        return Integer.toString(param);
    }

    @GetMapping("/bar")
    public String wrapped(@ModelAttribute @Valid Wrapper bean) {
        return Integer.toString(bean.param);
    }

    static class Wrapper {

        @Min(1)
        int param;

        public void setParam(final int param) {
            this.param = param;
        }
    }
}

测试

public class MyControllerTest {

    MyController controller = new MyController();
    MockMvc mockMvc = MockMvcBuilders
            .standaloneSetup(this.controller)
            .build();

    @Test // fails
    public void unwrapped() throws Exception {
        this.mockMvc.perform(get("/foo")
                .param("param", "0"))
                .andExpect(status().isBadRequest());
    }

    @Test // passes
    public void wrapped() throws Exception {
        this.mockMvc.perform(get("/bar")
                .param("param", "0"))
                .andExpect(status().isBadRequest());
    }
}

要在 spring 中启用(解包)方法参数验证,必须使用 @Validated 注释控制器,并且必须将 MethodValidationPostProcessor 添加到上下文中.
是否可以将 MethodValidationPostProcessor bean 添加到独立设置中?
问题可能会简化为如何将 BeanPostProcessor 添加到独立的 MockMvc 设置中?

To enable (unwrapped) method parameter validation in spring the controller has to be annotated with @Validated and the MethodValidationPostProcessor must be added to the context.
Is it possible to add the MethodValidationPostProcessor bean to the standalone setup ?
The question might be reduced to how to add a BeanPostProcessor to a standalone MockMvc setup ?

推荐答案

不,不幸的是,在使用 MockMvcBuilders.standaloneSetup() 时这是不可能的,因为这会在幕后创建一个 StubWebApplicationContext

这篇关于如何为独立的 MockMvc 启用控制器参数验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 20:45