springunit-testingspring-mvcbean-validationjsr

Test @Valid annotation with SpringMVC Maven


I am working on the chapter 5 example of the book Spring in Action 4. When I am running the Test classes I found one of the @Valid test is not working, it appears as if the validation never occured(returned status code of 302 and view's name is "/spitter/null"). However, it works fine when I run it in Tomcat.

The validatioon jars(hibernate-validator and its dependencies) are loaded with Maven.

The whole project is on github.

Any ideas?

test code snippet:

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes={RootConfig.class, WebConfig.class})
public class SpitterControllerTest {
    @Test
    public void shouldFailValidationWithNoData() throws Exception {
        SpitterRepository mockRepository = mock(SpitterRepository.class);    
        SpitterController controller = new SpitterController(mockRepository);
        MockMvc mockMvc = standaloneSetup(controller).build();

        mockMvc.perform(post("/spitter/register"))
            .andExpect(status().isOk())
            .andExpect(view().name("registerForm"))
            .andExpect(model().errorCount(5))
            .andExpect(model().attributeHasFieldErrors(
                "spitter", "firstName", "lastName", "username", "password", "email"));
    }
}

SpitterController snippet:

  @RequestMapping(value="/register", method=POST)
  public String processRegistration(
      @Valid Spitter spitter, 
      Errors errors) {
    if (errors.hasErrors()) {
      return "registerForm";
    }

    spitterRepository.save(spitter);
    return "redirect:/spitter/" + spitter.getUsername();
  }

Spitter snippet:

@NotNull
  @Size(min=5, max=16)
  private String username;

  @NotNull
  @Size(min=5, max=25)
  private String password;

  @NotNull
  @Size(min=2, max=30)
  private String firstName;

  @NotNull
  @Size(min=2, max=30)
  private String lastName;

  @NotNull
  @Email
  private String email;

Thanks a lot!


Solution

  • I tried this post's best answer and it worked. I changed the hibernate-validator version from 5.4.1.final to 5.2.4.final in pom. The github project is updated as well.