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]
我的配置有什麼問題?