ONJava.com -- The Independent Source for Enterprise Java
oreilly.comSafari Books Online.Conferences.

advertisement

AddThis Social Bookmark Button

Test-Driven Development Using StrutsTestCase
Pages: 1, 2, 3, 4

StrutsTestCase in Practice

To test this action using StrutsTestCase, we create a new class that extends the MockStrutsTestCase class. This class provides methods to build a simulated HTTP request, to call the corresponding Struts action, and to verify the application state once the action has been completed.



Imagine an online accommodation database with a multi-criteria search function. The search function is implemented by the /search.do action. The action will perform a multi-criteria search based on the specified criteria and places the result list in a request-scope attribute named results. For example, the following URL should display a list of all accommodation results in France:


/search.do?country=FR

Now suppose we want to implement this method using a test-driven approach. We write the action class and update the Struts configuration file. We also write the test case to test the (empty) action class. Using a strict test-driven development approach, we write the test case first, and then implement the code to match the test case. In practice, the exact order may vary depending on the code to be tested.

The initial test case will look like this:


public void testSearchByCountry() {
  setRequestPathInfo("/search.do");
  addRequestParameter("country", "FR");
  actionPerform();
}

Here we set up the path to call (setRequestPathInfo()) and add a request parameter (addRequestParameter()). Then we invoke the action class with actionPerform(). This will verify the Struts configuration and call the corresponding action class, but will not test what the action actually does. To do that, we need to verify the action results.


public void testSearchByCountry() {
  setRequestPathInfo("/search.do");
  addRequestParameter("country", "FR");
  actionPerform();
  verifyNoActionErrors();
  verifyForward("success");
  assertNotNull(request.getAttribute("results"));
}

Here we check three things:

  • There were no ActionError messages (verifyNoActionErrors()).
  • The "success" forward was returned.
  • The results attribute was placed in the request scope.
If we were using tiles, we could also check that the "success" forward actually points to the right tiles definition, using verifyTilesForward():

public void testSearchByCountry() {
  setRequestPathInfo("/search.do");
  addRequestParameter("country", "FR");
  actionPerform();
  verifyNoActionErrors();
  verifyTilesForward("success",
                     "accommodation.list.def");
  assertNotNull(request.getAttribute("results"));
}

Pages: 1, 2, 3, 4

Next Pagearrow