Java 使用JUnit测试时,Spring MVC中的Hibernate验证器不工作
我在JUnit中测试bean验证时遇到了一个问题 下面是我的Spring MVC控制器的代码片段:Java 使用JUnit测试时,Spring MVC中的Hibernate验证器不工作,java,spring-mvc,junit,bean-validation,Java,Spring Mvc,Junit,Bean Validation,我在JUnit中测试bean验证时遇到了一个问题 下面是我的Spring MVC控制器的代码片段: @RequestMapping(value = "/post/new", method = RequestMethod.POST) public String newPost(@Valid Post post, Errors errors, Principal principal) throws ParseException { if (errors.hasErrors()) {
@RequestMapping(value = "/post/new", method = RequestMethod.POST)
public String newPost(@Valid Post post, Errors errors, Principal principal) throws ParseException {
if (errors.hasErrors()) {
return "newpost";
}
User user = userService.findUser(principal.getName());
post.setUser(user);
postService.newPost(post);
return "redirect:/";
}
下面是我的bean片段:
public class Post implements Serializable {
private User user;
@NotNull
@Size(min = 1, max = 160)
private String message;
}
运行webapp时,验证非常有效。例如,当我添加一个长度为零的消息的新帖子时,我得到消息字段error
但是,我无法在JUnit测试中重现这种情况:
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = {WebConfig.class, RootConfig.class})
@ActiveProfiles("test")
public class PostControllerTest {
private PostService postServiceMock;
private UserService userServiceMock;
private PostController controller;
private MockMvc mockMvc;
private TestingAuthenticationToken token;
@Before
public void setUp() throws Exception {
postServiceMock = mock(PostService.class);
userServiceMock = mock(UserService.class);
controller = new PostController(postServiceMock, userServiceMock);
mockMvc = standaloneSetup(controller).build();
token = new TestingAuthenticationToken(new org.springframework.security.core.userdetails.User("test", "test", AuthorityUtils.createAuthorityList("ROLE_USER")), null);
}
@Test
public void testNewPost() throws Exception {
User user = new User();
user.setUsername("test");
Post post = new Post();
post.setUser(user);
post.setMessage("test message");
when(userServiceMock.findUser(user.getUsername())).thenReturn(user);
mockMvc.perform(post("/post/new").principal(token).param("message", post.getMessage())).andExpect(redirectedUrl("/"))
.andExpect(model().attribute("post", post));
mockMvc.perform(post("/post/new").principal(token).param("message", "")).andExpect(model().attributeHasFieldErrors("post", "message"));
}
当使用空消息参数触发第二个POST请求时,没有验证错误,我一直收到以下消息:
java.lang.AssertionError: No errors for attribute: [post]
我的配置有什么问题吗?已经解决了。问题出在Hibernate Validator 5.1.3版本中。切换到5.2.2解决了问题