0
我在JUnit中遇到了测试Bean验证的问题。在使用JUnit进行测试时,Spring MVC中的Hibernate验证器不工作
这里是我的Spring MVC控制器的代码片段:
@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的片段:在运行Web应用程序时
public class Post implements Serializable {
private User user;
@NotNull
@Size(min = 1, max = 160)
private String message;
}
验证的伟大工程。例如,当我添加具有零长度消息的新帖子时,我会收到消息字段错误。
不过,我不能在我的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]
我的配置有什么问题?