Reputation: 1225
I'm trying to write an integration test for a Spring WebApp I'm working on. At one point during the process I'm pulling the list of errors out of a BindingResult
using this code:
BindingResult checkMe = (BindingResult)mv.getModelMap().get("org.springframework.validation.BindingResult.module");
assertEquals(1, check.getErrorCount());
//Check to make sure it is the right field that errored, and had the right error.
if(check.hasErrors()){
List<ObjectError> errors = checkMe.getAllErrors();
assertEquals(1, errors.size());
ObjectError tester = errors.get(0);
assertEquals("Range", tester.getCode());
assertEquals("must be between 0 and 365", tester.getDefaultMessage());
}
I want to add a line that will assert that the field that is throwing the error is in fact "daysToComplete". I know the information is in there somewhere because checkMe.getAllErrors().toString()
returns:
[Field error in object 'module' on field 'daysToComplete': rejected value [1000]; codes [Range.module.daysToComplete,Range.daysToComplete,Range.int,Range]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [module.daysToComplete,daysToComplete]; arguments []; default message [daysToComplete],365,0]; default message [must be between 0 and 365]]
How do I just get the field itself? I've looked through the documentation and asked google but nothing seems to come up...
Upvotes: 4
Views: 10065
Reputation: 119
public String nameMethod(@ModelAttribute Client client, BindingResult result) {
for (ObjectError error : result.getAllErrors()) { // 1.
String fieldErrors = ((FieldError) error).getField(); // 2.
System.out.println(fieldErrors);
}
}
Now it is possible to return the error to the user and tell him which field he should verify.
Greetings.
Upvotes: 5
Reputation:
Your ObjectError is likely an instance of FieldError, which extends ObjectError. The FieldError should have a getField() method on it, which will tell you the name. Try the following (untested):
if (check.hasErrors()){
List<ObjectError> errors = checkMe.getAllErrors();
assertEquals(1, errors.size());
FieldError tester = null;
if (errors.get(0) instanceof FieldError) {
tester = errors.get(0);
} else {
assertFail("Wrong binding result error type.");
}
assertEquals("daysToComplete", tester.getField());
assertEquals("Range", tester.getCode());
assertEquals("must be between 0 and 365", tester.getDefaultMessage());
}
Upvotes: 7