daydreamer
daydreamer

Reputation: 91939

How to mock method calls of mock objects?

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

Answers (2)

NamshubWriter
NamshubWriter

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

Pace
Pace

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

Related Questions