作者:Willpower
來源:Rifoo Technology(http://www.rifoo.com)
時間:2006-01-13
備註:轉載請保留以上聲明
**/
我們前面已經實現了簡單的視圖,下面是我們做測試的時間了。Web MVC的易測試性是它的一大優點。我們接下來可以看到一段優雅的測試代碼來測試用戶接口的核心部分。
2.4.1. How do I do that?
在這個測試用例中,我們簡單的去調用控制器,並且確定能夠返回正確的模型給我們。首先,我們編寫一個簡單的JUnit test case來調用BikesController
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);
}
}
我們必須加載配置文件來測試Spring正常的加載每個bean。這裏我們用Spring提供的FileSystemXmlApplicationContext類來加載上下文配置。
接下來,我們要測試驗證器,看它是否能夠正確的驗證錯誤。
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( ));
}
小結:我們現在已經完成了第二章的修改部分,這一章中我們學習了Spring MVC的簡單用法,並且結合書中的代碼進行了簡單的補充。下一章中,我和大家一起繼續學習Spring和其他用戶接口框架的集成,如Struts和JSF的結合。