Servlet mocking with Mockito

When writing custom servlets, it can be quite useful to unit test them.  In my case, I used a combination of testng and mockito.  The basic idea is simple; mock a HttpServletRequest, and a HttpServletResponse and pass them to the custom servlet.  There is a bit more too it, so here’s an example.

final HttpServletRequest httpServletRequest = mock(HttpServletRequest.class);
when(httpServletRequest.getPathInfo()).thenReturn("/lineup/world.xml");
final HttpServletResponse httpServletResponse = mock(HttpServletResponse.class);
final StubServletOutputStream servletOutputStream = new StubServletOutputStream();
when(httpServletResponse.getOutputStream()).thenReturn(servletOutputStream);
final ServletConfig servletConfig = mock(ServletConfig.class);
when(servletConfig.getInitParameter("defaultPool")).thenReturn("testpool1");

This sets up an HttpServletRequest, an HttpServletResponse, a ServletConfig where i can pass in parameters that the container would have read from web.xml, and a “StubServletOutputStream”, which is just a convenient wrapper around a ByteArrayOutputStream.

My StubServletOutputStream looks like this:

public class StubServletOutputStream extends ServletOutputStream {
 public ByteArrayOutputStream baos = new ByteArrayOutputStream();
   public void write(int i) throws IOException {
    baos.write(i);
 }
}

It’s necessary to init() the servlet, something the container would normally do:

final MyServlet myServlet = new MyServlet();
myServlet.init(servletConfig);

Finally; I invoke my servlet, and check the output:

restCacheServlet.doGet(httpServletRequest, httpServletResponse);
final byte[] data = servletOutputStream.baos.toByteArray();
Assert.assertNotNull(data);
Assert.assertTrue(data.length > 0);

Similar Posts

  • restcache

    I recently found myself in a situation where mission-critical software was suffering from performance problems due to relying on a remote API which was both slow (as slow as 11sec / transaction), and unreliable.   In this case, it turned out that there were multiple applications accessing this API, and every individual application was affected….

  • DOT4J

    I’ve recently been quite interested in Graph languages, not for Graph Databases, but for representing information, in code that is essentially “things” and “relationships”. For example, one perspective on Organizations is that they are simply representable as people, systems and the information that flows between them. Those three building blocks are, in theory, enough to…

  • Reading Paradox Files

    Back in the day, Paradox was a pretty amazing database.  I recently had a reason to read some Paradox files for a friend, who had a client with a Paradox database.  They needed their data out of the database to insert into something more modern. Googling for the file format of a Paradox DB didn’t…

  • TNT

    If you haven’t read this book, I highly recommend it.  I discovered it in high school and finally purchased my first copy at the now-gone Duthie Books in Kitsilano.  Without going into the details of the book, the author uses a simple Peano arithmetic called Typographical Number Theory  (TNT) to illustrate some of his points. An example…

10 Comments

  1. hi, nice trick! I have introduced a minor change so the class looks like this:

    public class FakeServletOutputStream extends ServletOutputStream {
    private ByteArrayOutputStream baos = new ByteArrayOutputStream();
    public void write(int i) throws IOException {
    baos.write(i);
    }

    public String getContent() {
    return baos.toString();
    }
    }

  2. Is there a way to setup the context too? In my app, i use the context to store Database things like status of something , so i dont have to query the db everytime i open my formulars, they change never and now i want to test an method like getIdFromRequest or getStatusFromContext. Productioncode works but i have to refactor it and i have no tests, just a few integration tests. Maybe there is a tweak to init the context inside my servlet .

    greetings Lordi

  3. Thanks Man. It worked for me.
    This code is pure gold. I was struck for 3hrs on mocking invoking the servlet, and finally it worked.

    Thanks a lot

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.