Skip to Main Content
Spring: A Developer's Notebook
book

Spring: A Developer's Notebook

by Bruce Tate, Justin Gehtland
April 2005
Intermediate to advanced content levelIntermediate to advanced
216 pages
4h 44m
English
O'Reilly Media, Inc.
Content preview from Spring: A Developer's Notebook

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 { ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

JavaBeans Unleashed

JavaBeans Unleashed

Dr. Donald Doherty, Rick Leinecker
Beginning Spring

Beginning Spring

Mert Caliskan, Kenan Sevindik, Rod Johnson, Jürgen Höller
Hibernate Search in Action

Hibernate Search in Action

Emmanuel Bernard, John Griffin

Publisher Resources

ISBN: 0596009100Supplemental ContentErrata Page