Java Reference
In-Depth Information
with Spring's web MVC framework.” Fortunately they can be used with any web applica-
tion, whether it's based on Spring MVC or not.
3 The mock objects work for Servlet 3.0 as well, with some minor exceptions listed in the JavaDocs.
The next listing shows a JUnit test for the doGet method of my “Hello, World!” servlet.
Listing 10.9. HelloServletJavaTest : a servlet test class using mock objects
import static org.junit.Assert.*;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
public class HelloServletJavaTest {
@Test
public void testDoGet() {
HelloServlet servlet = new HelloServlet();
MockHttpServletRequest req = new MockHttpServletRequest();
MockHttpServletResponse resp = new MockHttpServletResponse();
try {
servlet.doGet(req, resp);
assertEquals("Hello, Servlet!",
resp.getContentAsString().trim());
} catch (Exception e) {
e.printStackTrace();
}
}
}
The try/catch blocks do their best to bury the essence in ceremony, but the intent is
clear. The method instantiates the servlet and mock objects representing the servlet request
and servlet response classes, and then it invokes the doGet method on the servlet with the
mocks as arguments. The good part is that the MockHttpServletResponse class has
a method called getContentAsString , which captures the data written to the output
writer in the servlet so it can be compared to the expected answer.
Note that the mock classes are being used not as Spring beans in the traditional sense (as
they are in chapter 7 on Spring), but simply as an available API.
 
Search WWH ::




Custom Search