entrada antigua del 23/3/2011 – old post from 3/23/2011
Behind this long title, today I would like to show an easy but powerful technique to unit test Java Servlets.
This method focuses in the fact that most of the Java Servlets are just returning plain text contents, usually HTML or XML.
For a proper unit test on the Java Servlet to run outside a web container, we need to mock the HttpServletRequest and HttpServletResponse objects. Mock, in short, is a term to refer to a double object, that is, an object that exists solely for the purpose of testing the unit at hand, with the same interface that an actual runtime object but with a different behavior, based on expectations.
It is not the purpose of this post to talk about mocks and other unit testing techniques. If you feel curious you can get more on the subject on this excellent paper from Martin Fowler (yes, ‘that’ Fowler guy): Mocks aren’t Stubs, by Martin Fowler.
With that being said, let’s go to the point. What we want to achieve is to test the output of a Java Servlet in different situations, asserting that this output contains certain strings of text. We will need to mock the request and response objects.