I am trying to assert two errors due to two given constraints to my form. My form has two constraints on its single field:
@Data
@NoArgsConstructor
@NotExistingGroup(groups = SecondGroupValidation.class)
public class GroupForm {
@NotBlank(groups = FirstGroupValidation.class)
@Size(min = 2, max = 30, groups = FirstGroupValidation.class)
private String name;
}
With the following test, I want to trigger both the @NotBlank
and @Size
validation and assert both raised errors:
@Test
void givenGroupEmptyName_groupPost_assertErrors() throws Exception {
mvc.perform(post("/groups/add").param("name", ""))
.andDo(print())
.andExpect(status().isOk())
.andExpect(view().name("groups-add"))
.andExpect(model().hasErrors())
.andExpect(model().attributeErrorCount("groupForm", 2))
.andExpect(model().attributeHasFieldErrorCode("groupForm", "name", "NotBlank"))
.andExpect(model().attributeHasFieldErrorCode("groupForm", "name", "Size"));
}
The mvc doPrint()
method shows both errors are given
ModelAndView:
View name = groups-add
View = null
Attribute = groupForm
value = GroupForm(name=)
errors = [Field error in object 'groupForm' on field 'name': rejected value []; codes [NotBlank.groupForm.name,NotBlank.name,NotBlank.java.lang.String,NotBlank]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [groupForm.name,name]; arguments []; default message [name]]; default message [must not be blank], Field error in object 'groupForm' on field 'name': rejected value []; codes [Size.groupForm.name,Size.name,Size.java.lang.String,Size]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [groupForm.name,name]; arguments []; default message [name],30,2]; default message [size must be between 2 and 30]]
However, the test breaks with the following error
java.lang.AssertionError: Field error code expected:<Size> but was:<NotBlank>