Home > Java > Two different mocking approaches

Two different mocking approaches

Whether you choose to choose to adopt TDD or a more traditional approach, you will test your classes in isolation. This usually mean you code with interfaces and inject your dependencies in your classes.

Last year, I had to test a servlet. Servlets are the showcase to demonstrate out-of-container testing because of their dependencies to said container in their doXxx() method. Every one of these methods has a dependency on HttpServletRequest and HttpServletResponse. Both are interfaces that have no concrete implementations in the Servlet API. So, basically, in your tests, you’re stuck with three options:

  1. Use your container implementations (yuck!),
  2. Create your own implementations (rather time-consuming),
  3. Use already available implementations that have no dependencies.

Choosing option the 3rd option, I found this little jewel, MockRunner. MockRunner put at your dispositions mock implementations for the following API and frameworks:

  • JNDI
  • EJB2,
  • JDBC,
  • JMS,
  • Servlet,
  • TagLib,
  • Struts.

All these mock implementations run as they should. For example, if you put an object into a mock session at the start of your test, and if you’re still in the same request afterwards, you can check the object is still here. Let’s consider the following servlet method to test:

@Override
protected void doGet(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletException,
        IOException {

    String action = aRequest.getParameter("action");

    HttpSession session = aRequest.getSession();

    Object object = session.getAttribute("number");

    int number = object == null ? 0 : (Integer) object;

    if ("add".equals(action)) {

        number++;

        session.setAttribute("number", number);

    } else if ("remove".equals(action)) {

        number--;

        session.setAttribute("number", number);

    } else if ("reset".equals(action)) {

        session.setAttribute("number", 0);
    }
}

How do you test this code with MockRunner? The first thing is to inherit from com.mockrunner.servlet.BasicServletTestCaseAdapter. Code follows:

public class MockRunnerTest extends BasicServletTestCaseAdapter {

    /**
     * Setup the servlet to test.
     */
    @Override
    public void setUp() throws Exception {

        super.setUp();

        createServlet(SessionServlet.class);
    }

    /**
     * Test method for
     * {@link SessionServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)}.
     *
     * @throws IOException
     * @throws ServletException
     */
    public void testDoGetAdd() throws ServletException, IOException {

        addRequestParameter("action", "add");

        doGet();

        Object object = getSessionAttribute("number");

        assertTrue(Integer.class.isAssignableFrom(object.getClass()));

        int number = (Integer) object;

        assertEquals(1, number);
    }

    /**
     * Test method for
     * {@link SessionServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)}.
     *
     * @throws IOException
     * @throws ServletException
     */
    public void testDoGetRemove() throws ServletException, IOException {

        addRequestParameter("action", "remove");

        doGet();

        Object object = getSessionAttribute("number");

        assertTrue(Integer.class.isAssignableFrom(object.getClass()));

        int number = (Integer) object;

        assertEquals(-1, number);
    }

    /**
     * Test method for
     * {@link SessionServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)}.
     *
     * @throws IOException
     * @throws ServletException
     */
    public void testDoGetReset() throws ServletException, IOException {

        addRequestParameter("action", "reset");

        doGet();

        Object object = getSessionAttribute("number");

        assertTrue(Integer.class.isAssignableFrom(object.getClass()));

        int number = (Integer) object;

        assertEquals(0, number);
    }
}

Testing our servlet is fine like this although using MockRunner has several limitations:

  • you have to inherit from MockRunner’s base classes,
  • thus, you’re stuck with using JUnit v3. You cannot use TestNG or JUnit v4 either,
  • you are limited in what you can test out-of-the-box. If, for a reason or another, you decided to create a super servlet with additional functionalities, you are condemned to extend the MockRunner framework. Similarly, if a new API emerge, you have to create your own adapters,
  • you have to remember to call super.setUp() in your setUp() method (really not a good idea),
  • last, but not least, MockRunner project has seen no activity since summer ’08.

Then I got interested in Mockito. Mockito is a “true” Mock framework that enhances your interfaces and you classes with CGLIB to provide stubs for methods: that is you provide code that is chained to method invocation. Mockito seems to be very hype nowadays, but the trend is still catching. The following code shows you a test class made with Mockito:

public class MockitoTest {

    /** Servlet under test. */
    private SessionServlet servlet;

    /** Mock request. */
    private HttpServletRequest request;

    /** Mock response. */
    private HttpServletResponse response;

    /** Mock session. */
    private HttpSession session;

    /** Session's attribute map. */
    private Map attributes;

    /** Request's parameter map. */
    private Map parameters;

    /**
     * Launches Mockito configuration from annotations.
     */
    @Before
    public void setUp() {

        attributes = new HashMap();
        parameters = new HashMap();

        servlet = new SessionServlet();
        request = mock(HttpServletRequest.class);
        response = mock(HttpServletResponse.class);
        session = mock(HttpSession.class);

        when(request.getSession()).thenReturn(session);
        when(request.getParameterMap()).thenReturn(parameters);
        when(request.getParameter(anyString())).thenAnswer(new Answer() {

            /**
             * @see org.mockito.stubbing.Answer#answer(org.mockito.invocation.InvocationOnMock)
             */
            @Override
            public Object answer(InvocationOnMock aInvocation) throws Throwable {

                String key = (String) aInvocation.getArguments()[0];

                return parameters.get(key);
            }
        });

        when(session.getAttribute(anyString())).thenAnswer(new Answer() {

            /**
             * @see org.mockito.stubbing.Answer#answer(org.mockito.invocation.InvocationOnMock)
             */
            @Override
            public Object answer(InvocationOnMock aInvocation) throws Throwable {

                String key = (String) aInvocation.getArguments()[0];

                return attributes.get(key);
            }
        });

        Mockito.doAnswer(new Answer() {

            /**
             * @see org.mockito.stubbing.Answer#answer(org.mockito.invocation.InvocationOnMock)
             */
            @Override
            public Object answer(InvocationOnMock aInvocation) throws Throwable {

                String key = (String) aInvocation.getArguments()[0];
                Object value = aInvocation.getArguments()[1];
                attributes.put(key, value);

                return null;
            }

        }).when(session).setAttribute(anyString(), anyObject());
    }

    /**
     * Test method for
     * {@link SessionServlet#doGet(HttpServletRequest, HttpServletResponse)} .
     *
     * @throws IOException
     * @throws ServletException
     */
    @Test
    public void testDoGetAdd() throws ServletException, IOException {

        parameters.put("action", "add");
        servlet.doGet(request, response);

        Object object = attributes.get("number");

        assertNotNull(object);
        assertTrue(Integer.class.isAssignableFrom(object.getClass()));

        int number = (Integer) object;

        assertEquals(1, number);
    }

    /**
     * Test method for
     * {@link SessionServlet#doGet(HttpServletRequest, HttpServletResponse)} .
     *
     * @throws IOException
     * @throws ServletException
     */
    @Test
    public void testDoGetRemove() throws ServletException, IOException {

        parameters.put("action", "remove");
        servlet.doGet(request, response);

        Object object = attributes.get("number");

        assertNotNull(object);
        assertTrue(Integer.class.isAssignableFrom(object.getClass()));

        int number = (Integer) object;

        assertEquals(-1, number);
    }

    /**
     * Test method for
     * {@link SessionServlet#doGet(HttpServletRequest, HttpServletResponse)} .
     *
     * @throws IOException
     * @throws ServletException
     */
    @Test
    public void testDoGetReset() throws ServletException, IOException {

        parameters.put("action", "reset");
        servlet.doGet(request, response);

        Object object = attributes.get("number");

        assertNotNull(object);
        assertTrue(Integer.class.isAssignableFrom(object.getClass()));

        int number = (Integer) object;

        assertEquals(0, number);
    }
}

Mockito suffers from a severe lack of documentation for newbies. Though the Mockito class is well documented, I think an external presentation about the philosophy and the architecture would have been in order. This is a limitation I could adress to many Google Code project, though.

IMHO, MockRunner is more integrated with the API, hiding implementation details whereas with Mockito, you need to know about the implementation in order to provide adequate stubs. Mockito’s test class is about twice the code size than MockRunner’s. Thus, I would keep using MockRunner for classes using their integrated API, though it would force me to use an older version of JUnit, and use Mockito where there’s no such constraint.

In conclusion, I would admit both these testing harness have very different approaches and very different scopes. I find Mockito a bit complex to use, still.

To make your own mind:

email
Send to Kindle
Categories: Java Tags: , , , ,
  1. Hicham
    May 10th, 2009 at 19:49 | #1

    Hello Nicolas,

    Nice post.

    Did you try Spring Mocks? I used it only to mock a servlet container and it seemed to me much easier to use than MockRunner and Mockito. Do you know how it compares?

    Thanks.

    Hicham

  2. May 10th, 2009 at 21:41 | #2

    Hi,

    Spring Mock is about the same as MockRunner but in a more limited scope. For example, Spring does not provide mock implementations for the JDBC API, nor for the JMS API – it was what I needed at the time – though it provides such implementations for the Portlet API.

    In a situation where I already have Spring as a dependency in my project, I would prefer using Spring Mock over MockRunner in order to emulate web or JNDI objects, switching to MockRunner for other needs. I would only use Mockito in dire need when an API is supported by neither of them. Since you’re working on portlets, I understand the added value of Spring Mock in you case.

    I’m all yours if you have other questions.

    Nicolas

  1. May 21st, 2009 at 00:24 | #1