3

Let's say I have a model class like this:

public class User {
    @NotEmpty(message = "Email is required")
    private String email;
}

I want to be able to unit test for the custom error message "Email is required"

So far, I have this Unit Test code which works, but does not check for the error message.

@Test
public void should_respond_bad_request_with_errors_when_invalid() throws Exception
{
    mock().perform(post("/registration/new"))
            .andExpect(status().isBadRequest())
            .andExpect(view().name("registration-form"))
            .andExpect(model().attributeHasFieldErrors("user", "email"));
}
leojh
  • 7,160
  • 5
  • 28
  • 31
  • Possible duplicate of [Good patterns for unit testing form beans that have annotation-based validation in Spring MVC](http://stackoverflow.com/questions/9516079/good-patterns-for-unit-testing-form-beans-that-have-annotation-based-validation) – Jimmy T. Sep 09 '16 at 18:04

2 Answers2

1

Seems you can't.

But I suggest you work around through the attributeHasFieldErrorCode method.

Having the following:

@NotNull(message="{field.notnull}")
@Size(min=3, max=3, message="{field.size}")
public String getId() {
    return id;
}

I have in my test methods the following (in case my data fails for Minimum or Maximum constraints, it belongs to the @Size annotation)

.andExpect(model().attributeHasFieldErrorCode("persona", "id", is("Size")))

or with

.andExpect(model().attributeHasFieldErrorCode("persona", "id", "Size"))

The method has two versions, with and without Hamcrest

Even when you use message = "Email is required" (raw/direct content) and I use message="{field.size}") the key to be used from a .properties file, our message attribute content belongs practically for a unique kind of annotation. In your case for a @NotNull and in my case for a Size.

Therefore, in some way does not matter what is the message (raw or key), the important is that the owner of that message (in this case the annotation) did its work and it has been validated through the attributeHasFieldErrorCode method.

Do not confuse with the similar methods names: attributeHasFieldErrors and attributeHasFieldErrorCode.

Manuel Jordan
  • 15,253
  • 21
  • 95
  • 158
-1

I have had the same issue. I have found some solution described below. The main idea is to check error code, not the error message.

BindingResult bindingResult = (BindingResult)
mock().perform(post("/registration/new")).andReturn().getModelAndView().getModelMap().get("org.springframework.validation.BindingResult.user");

 assertEquals(bindingResult.getFieldError(email).getCode(), "error.code");
fashuser
  • 2,152
  • 3
  • 29
  • 51