WildDev WildDev - 1 year ago 144
Java Question

Mockito - how to answer with custom object

Trying to test the construction like this:

@RequestMapping(value = "/test", method = POST)
public ResponseEntity test(@RequestBody TestRequest request, Errors errors) {

testValidator.validate(request, errors); // Spring Validator interface impl

if (errors.hasErrors())
return new ResponseEntity(HttpStatus.BAD_REQUEST);

return new ResponseEntity(HttpStatus.OK);

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

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ExampleTest {

private TestRestTemplate testRestTemplate;

private TestValidator testValidator;

public void test() {

doAnswer(new Answer<Errors>() {

public Errors answer(InvocationOnMock invocation) throws Throwable {

Errors errors = spy((Errors) invocation.getArguments()[1]);
//errors.rejectValue("id", "id", "id rejected");


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
still returns
despite on
test block and the assertion fails because of HTTP status
. I expect the
object will become the spy with specified behaviour right after
call but seems I'm doing something wrong.

So, how to return a custom object using Mockito's

Answer Source

Don't use postForEntity in your test, because that makes it an integration test of the framework itself, plus the actual class that you're testing.

Just make your own Errors object, which may or may not be a mock. If it's a mock, then you can set it up as follows.


Then your test can look like this.

public void test() {
  ResponseEntity re = objectThatYoureTesting.test(mockTestRequest, mockErrors);
  assertEquals(HttpStatus.BAD_REQUEST, re.getStatusCode());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download