Reputation: 91939
Consider this example
resp.getWriter().write(Collections.singletonMap("path", file.getAbsolutePath()).toString());
where resp
is HttpServletResponse
and is mocked.
I am using JMock
Mockery to mock these
My code looks like
try {
atLeast(1).of(resp).getWriter().write(String.valueOf(any(String.class)));
} catch (IOException e) {
e.printStackTrace();
}
will(returnValue("Hello"));
When I run this, I get
java.lang.NullPointerException
Which I believe is coming since getWriter()
is not sending anything back
How do I handle this situation?
Upvotes: 2
Views: 455
Reputation: 24286
I would not use a mock for Writer
. You want to test that the output gets written, not the interaction that causes the output to get written.
Instead, use a real object:
HttpServletResponse mockResponse
= context.mock(HttpServletResponse.class);
StringWriter writer = new StringWriter();
...
atLeast(1).of(mockResponse).getWriter();
will(returnValue(writer));
Upvotes: 1
Reputation: 43817
You need 2 mock objects.
HttpServletResponse resp = context.mock(HttpServletResponse.class);
Writer writer = context.mock(Writer.class);
...
atLeast(1).of(resp).getWriter();
will(returnValue(writer));
allowing(writer).write(with(any(String.class));
Upvotes: 3