Daniil Molchanov
Daniil Molchanov

Reputation: 133

Hibernate Validator in Spring MVC not working when testing with JUnit

I have encountered a problem with testing bean validation in JUnit.

Here is code fragment of my Spring MVC controller:

@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:/";
}

Here is fragment of my bean:

public class Post implements Serializable {
    private User user;

    @NotNull
    @Size(min = 1, max = 160)
    private String message;
}

Validation works great when running the webapp. For example, when I add a new post with zero-length message I get message field error.

However, I cannot reproduce this case in my JUnit test:

@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"));
}

When the second POST request is fired with empty message parameter there are no validation errors and I keep getting this message:

java.lang.AssertionError: No errors for attribute: [post]

What is wrong with my configuration?

Upvotes: 0

Views: 1151

Answers (1)

Daniil Molchanov
Daniil Molchanov

Reputation: 133

Figured it out. The problem was in Hibernate Validator 5.1.3 version. Switching to 5.2.2 solved the issue.

Upvotes: 2

Related Questions