Section 2.4. Running a Test

team bbl


2.4. 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.

2.4.1. 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 {         BikeValidator v = (BikeValidator) ctx.getBean("bikeValidator");         Bike bike = new Bike("test", "test", 1, "test", 2.00, "test");         Errors errs = new BindException(bike, "bike");         v.validate(bike, errs);         assertFalse(errs.hasErrors( ));         bike = new Bike( );         errs = new BindException(bike, "bike");         v.validate(bike, errs);         assertTrue(errs.hasErrors( ));     }

2.4.2. What just happened?

Instead of running the test case in the container, you simply fired the controller and tested the output. Since you didn't have to test the full user interface in context, you had to do much less work to make the test case go, and you could get a basic level of testing behind you. In the next chapter, you'll see how to integrate other user interface strategies into Spring.

    team bbl



    Spring. A developer's Notebook
    Spring: A Developers Notebook
    ISBN: 0596009100
    EAN: 2147483647
    Year: 2005
    Pages: 90

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net