测试Spring Controller方法时Bean验证问题

时间:2015-08-07 09:04:12

标签: spring spring-mvc testng hibernate-validator spring-test-mvc

我有一个看起来像这样的Spring RestController:

...
import javax.validation.Valid;
...
@RestController
@RequestMapping( value = "/users", consumes = { MediaType.APPLICATION_JSON }, produces = { MediaType.APPLICATION_JSON })
public class UserController
{
    @Autowired
    private UserService userService;

    @RequestMapping(method = RequestMethod.POST)
    public @ResponseBody User add(@RequestBody @Valid User user)
    {
        ...
    }
    ...
}
用户旁边的

PS @Valid :这就是我遇到问题的地方。

这是控制器的测试之一:

@ContextConfiguration(classes = { TestAppConfig.class, PersistenceConfig.class }, loader = AnnotationConfigWebContextLoader.class)
@WebAppConfiguration
public class UserControllerTest extends AbstractTestNGSpringContextTests
{
    @Autowired
    private UserController userController;

    @Test
    public void addTest()
    {
       User user = new User();
       ...
       userController.add(user);
       ...
    }
}

TestAppConfig看起来像这样:

@Configuration
@ComponentScan(basePackages = {Constants.BEANS_BASE_PACKAGE})
@PropertySource(value = { "classpath:application.properties" })
@EnableAspectJAutoProxy
@EnableWebMvc
class TestAppConfig extends WebMvcConfigurerAdapter
{
}

问题@Valid以外的所有内容都可以正常工作(调用服务)。这里,@Validjavax.validation.Valid注释,我希望用于简单验证(implementation = Hibernate Bean Validator)。但是,在我的测试中,我没有看到验证正在发生。但是,当我调用服务调用时,它们确实会发生。我能错过什么?

1 个答案:

答案 0 :(得分:0)

由于您直接在add上调用UserController方法,因此spring无法拦截您的请求并执行其验证魔法。最好使用MockMvc并对其执行请求,如下所示:

@ContextConfiguration(classes = { TestAppConfig.class, PersistenceConfig.class }, loader = AnnotationConfigWebContextLoader.class)
@WebAppConfiguration
public class UserControllerTest extends AbstractTestNGSpringContextTests
{
    @Autowired private WebApplicationContext wac;
    private MockMvc mvc;

    @Before
    public void setUp() {
        mvc = MockMvcBuilders.webAppContextSetup(wac).build();
    }

    @Test
    public void addTest()
    {
       User user = new User();
       ...
       mvc.perform(post('/users')
                   .content(...)
                   .contentType(...)
                   .accept(...))
       ...
    }
}

有关详细信息,请参阅spring test doc