Last Updated: February 25, 2016
· davewatts

Mocking HttpServletRequest / HttpServletResponse

Thanks to the way the classes for the Servlet API have been created, they are completely useless for anything except compiling against. If you try to mock the interfaces, you may well end up with the following:

Absent Code attribute in method that is not native or abstract in class file javax/servlet/http/Cookie

Your options are:
1. Depend on a real Servlets implementation, not the API
2. Implement the mocks yourself

The former means you're testing against specific 3rd party behaviour, and probably end up throwing a 50MB jar around

The latter means you have dozens of methods to implement, and don't get any niceties like EasyMock's invocation counting.

Both of these suck.

I used the second approach, in the following way

Autogenerate MockHttpServletRequest, implementing HttpServletRequest and add the following method

private void crapOut() {
    final StackTraceElement[] ste = Thread.currentThread().getStackTrace();
    String methodName = ste[2].getMethodName();
    throw new UnsupportedOperationException("Unimplemented method:" + methodName);

Make every method in the mock call that method, and return null/false/-1/whatever

Then use the mocks in place of real instances. Every method called by the code under test will fail thanks to crapOut(). Whenever you see one of these failures, implement the failing method and try again