Java Reference
In-Depth Information
The MockServletContext accepts one or more filters, but only one servlet
at a time. Starting at Ê , we've added the Stripes filter with its parame-
ters and the dispatcher servlet. We do not have to set up any mappings
because all requests go through all filters and the servlet of a Mock-
ServletContext .
Stripes also provides a mock object to simulate the session, Mock-
HttpSession , but it is not used unless you create an instance. This is
done at Ë .
Next, we need a user to be logged in for the tests to run properly. This
involves creating a mock user, courtesy of MockDataLoaderActionBean
(a convenience action bean that loads mock data for testing purposes),
and logging in with LoginActionBean :
Download email_26/src/stripesbook/test/stripesmock/ContactFormActionBeanTest.java
// Load mock user
MockRoundtrip trip = new MockRoundtrip(mockServletContext,
MockDataLoaderActionBean. class , mockSession);
trip.execute();
// Login mock user
trip = new MockRoundtrip(mockServletContext,
LoginActionBean. class , mockSession);
trip.setParameter("username", "freddy");
trip.setParameter("password", "nadia");
trip.execute("login");
As we can see, using the MockRoundtrip class is pretty simple. Indicate
the action bean to which we want to submit the request, attach a ses-
sion if needed, set the parameters we want to send, and call execute ( ).
Every test that we add will now benefit from this setup. Let's write a
test and learn more about MockRoundtrip .
Let's say we want to test the submission of a blank contact form. Since
the email field is required, this should result in a validation error. Here
is the test method:
Download email_26/src/stripesbook/test/stripesmock/ContactFormActionBeanTest.java
@Test
public void testEmailRequired() throws Exception {
MockRoundtrip trip = new MockRoundtrip(mockServletContext,
ContactFormActionBean. class , mockSession);
trip.execute("save");
ContactFormActionBean bean =
trip.getActionBean(ContactFormActionBean. class );
 
 
Search WWH ::




Custom Search