Question

Can I use Mockito to capture what was passed to the HttpServletResponse#sendError() method? I can't figure out how to do that.

Was it helpful?

Solution

You should use the verify method on Mockito to do this. Usually mocking HttpResponse isn't a pleasant experience though.

mockResponse = mock(HttpSR→);
//…
verify(mockResponse, times(1)).sendError(..);

As arguments to sendError you can then pass mockito matchers, which can do any check on the argument that you need.

OTHER TIPS

I think the poster wanted to know, how to retrieve the arguments that were passed to the method. You can use:

// given
HttpServletResponse response = mock(HttpServletResponse.class); 
ArgumentCaptor<Integer> intArg = ArgumentCaptor.forClass(Integer.class);
ArgumentCaptor<String> stringArg = ArgumentCaptor.forClass(String.class);
doNothing().when(response).sendError(intArg.capture(), stringArg.capture());

// when (do your test here)
response.sendError(404, "Not found");

// then (do your assertions here, I just print out the values)
System.out.println(intArg.getValue());
System.err.println(stringArg.getValue());

You might want to look at Mockito spies (chapter 13). For objects you can't mock, you can sometimes examine their internals and stub certain methods this way.

If you can post some sample code, I can take a look at it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top