Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Unit Test Spring MVC validation annotation error messages?

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"));
}
like image 658
leojh Avatar asked Nov 26 '25 16:11

leojh


1 Answers

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.

like image 139
Manuel Jordan Avatar answered Nov 28 '25 08:11

Manuel Jordan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!