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

  • jvmBasic 2.0

    I’ve always had a fascination with compilers.  As a Java geek, I’m also quite interested in the JVM.  In order to learn a little more about both, and as a way to contribute to the open source world, I decided to implement a compiler for BASIC.   So, jvmBasic consumes BASIC code and emits .class…

  • Quadrigacx API

    I’ve recently become very interested in blockchain, and that, naturally led me to Ethereum and Bitcoin.  From there, I got a little interested in online trading, but since I prefer not to have to think about trading, I started thinking about a trading bot.  Part of the work I needed to do was write a…

  • Ebean-DAO

    When building database ORM code, I prefer to use ebean, and I prefer to use DAO‘s. Since DAO’s are simple to make generic, I have a Generic DAO I use for all projects. I’ve finally decided to open-source my DAO code, and you can find it here https://github.com/teverett/ebean-dao.

  • Outlook for Mac Archives

    I recently had a reason to parse a large data set, for another project.  I decided that an ideal “large data set” would be my Outlook mail saved archives.  Sadly, Outlook for Mac doesn’t output PST files, it outputs OLM archives, which are, essentially, giant zip files full of XML.  I was coding this all…

  • 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….

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.