Running a Test

Now that you've implemented a few simple views, it's time to do a test. We'll simply do a lightweight request, outside of the servlet container.

Part of the beauty of Web MVC is that it's much easier to test. We'll show you a couple of simple test cases that exercise the core of the user interface pretty well.

How do I do that?

In this case, you're simply going to invoke the controller, and make sure that you get the appropriate model back. First, you can code a simple JUnit test case that invokes the BikesController (Example 2-20).

Example 2-20. ControllerTest.java

public class ControllerTest extends TestCase {

    private ApplicationContext ctx;

    public void setUp( ) throws Exception {
        ctx = new FileSystemXmlApplicationContext(
           "war/WEB-INF/rentaBikeApp-servlet.xml");
    }

    public void testBikesController( ) throws Exception {
        BikesController controller = (BikesController) 
           ctx.getBean("bikesController");
        ModelAndView mav = controller.handleRequest(null, null);
        RentABike store = (RentABike) mav.getModel( ).get("rentaBike");
        assertNotNull(store);
        assertTrue(store.getBikes( ).size( ) == 3);
    }
}

You have to load up the configuration file in order to test that Spring is loading the beans correctly. Spring provides the FileSystemXmlApplicationContext class to load the context configuration explicitly.

Next, we'll want to test the validator to make sure it catches errors appropriately (Example 2-21).

Example 2-21. ControllerTest.java

public void testBikeValidator( ) throws Exception { ...

Get Spring: A Developer's Notebook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.