Trying to test the construction like this:
@RequestMapping(value = "/test", method = POST)
public ResponseEntity test(@RequestBody TestRequest request, Errors errors) {
testValidator.validate(request, errors);
if (errors.hasErrors())
return new ResponseEntity(HttpStatus.BAD_REQUEST);
return new ResponseEntity(HttpStatus.OK);
}
The Errors
object is passed by framework and not by me, so there's no better way to change it's behaviour for the test except of using something like Mockito's Answer
:
doAnswer(new Answer<Errors>() {
@Override
public Errors answer(InvocationOnMock invocation) throws Throwable {
Errors errors = spy((Errors) invocation.getArguments()[1]);
//errors.rejectValue("id", "id", "id rejected");
doReturn(true).when(errors).hasErrors();
return errors;
}
}).when(testValidator).validate(any(), any());
ResponseEntity re = testRestTemplate
.postForEntity("/test", new TestRequest(213L), String.class);
assertEquals(HttpStatus.BAD_REQUEST, re.getStatusCode());
... but the problem is errors.hasErrors()
still returns false
despite on doAnswer
test block and the assertion fails because of HTTP status OK
. I expect the Errors
object will become the spy with specified behaviour right after .validate()
call but seems I'm doing something wrong.
So, how to return a custom object using Mockito's doAnswer
?
Aucun commentaire:
Enregistrer un commentaire