【问题标题】:Hibernate Validator in Spring MVC not working when testing with JUnit使用 JUnit 进行测试时,Spring MVC 中的 Hibernate Validator 不起作用
【发布时间】:2016-01-03 23:12:45
【问题描述】:

我在 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()) {
        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 时效果很好。例如,当我添加一条消息长度为零的新帖子时,我收到消息字段错误。

但是,我无法在我的 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]

我的配置有什么问题?

【问题讨论】:

    标签: java spring-mvc junit bean-validation


    【解决方案1】:

    想通了。问题出在 Hibernate Validator 5.1.3 版本中。切换到 5.2.2 解决了这个问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-23
      • 1970-01-01
      • 2016-02-04
      • 1970-01-01
      • 1970-01-01
      • 2014-01-25
      • 1970-01-01
      • 2015-05-17
      相关资源
      最近更新 更多