The Spring Framework provides a spring-mock.jarthat includes classes useful for
writing both unit tests and integration tests. We will focus on a very useful set of stubs for
testing web components in the org.springframework.mock.webpackage, including classes
such as MockHttpServletRequest, MockHttpServletResponse, and MockServletContext. These
are lightweight classes and can be used in any unit test, not just tests for Controllers.
Stubs vs. Mocks
While the names for the classes in spring-mock.jarbegin with mock, we argue that they are
in fact stubs. The term stubindicates that the class is unintelligent with no scripting or control
abilities. While mocks can be configured with expectations and programmable behavior, a
stub is merely a placeholder with simple predefined behavior.
In no way does this mean that the provided classes such as MockHttpServletRequestare
less than useful. These classes play a valuable role in testing web components, and the fact
that they are predefined saves plenty of time when writing tests.
Stubs are useful not only in testing situations, but also when integrating application lay-
ers. Stubs can help development teams deliver slices faster by allowing each layer to develop
at an independent rate. As layers are built out, they can use stubs as stand-ins for the depend-
ent layers. As layers complete their functionality, the stubs are replaced and testing continues.
Servlet API Stubs
The spring-mock.jarprovides a full array of stubs for the Servlet API, among other things.
These classes are simple to create, and for the most part behave exactly like their real-life
counterparts.
- MockHttpServletRequest
- MockHttpServletResponse
- MockHttpSession
- MockServletConfig
- MockServletContext
- MockPageContext
- MockRequestDispatcher
- MockFilterConfig
- MockExpressionEvaluator: Useful for testing JSP 2.0 components; requires jstl.jaron
the classpath
Controller Test Example
Let’s put these stubs to work testing a Controllerthat will expose the activateAccount()method
to the web. A client wishing to activate an account will use the HTTP POST method and provide
a request parameter named id. For simplicity’s sake, we will assume that an aspect of the system
has taken care of the security checks for user credentials and permissions.
The Controllercode is shown in Listing 10-9.
CHAPTER 10 ■TESTING SPRING MVC APPLICATIONS 297