測試Spring容器
在Junit的測試類中,繼承AbstractJUnit4SpringContextTests就可以進行Spring容器測試, 例如下面測試用例,
1 @RunWith(SpringJUnit4ClassRunner.class) 2 @ContextConfiguration(locations = { "/applicationContext.xml", 3 "/daoContext.xml" }) 4 public class TestSpring extends AbstractJUnit4SpringContextTests { 5 6 @Autowired 7 private ApplicationContext appContext; 8 9 @Autowired 10 private SessionFactory sessionFactory; 11 12 @Test 13 public void testSpringContext() { 14 EmpManager empMgr = (EmpManager) appContext.getBean("empManager"); 15 List<AttendType> types = empMgr.getAllType(); 16 for (AttendType type : types) { 17 System.out.println(type.getId() + "," + type.getAmerce()); 18 } 19 } 20 }
在AbstractJUnit4SpringContextTests中自帶一個applicationContext屬性變量,默認使用applicationContext.xml進行初始化,
在子類中可以在類上重新指定新的配置文件,並再次定義ApplicationContext私有成員, 從而在測試方法中使用,如上。
測試struts 的Action
struts2提供了StrutsSpringTestCase這個類用來在junit中做測試, 只需要將測試類繼承此類即可,
在測試方法中,將使用代理方法執行Action
在測試類中,通過重寫 getContextLocations方法,可以自定義配置文件,如下,
1 public class TestLoginAction extends StrutsSpringTestCase { 2 3 @Override 4 protected String[] getContextLocations() { 5 return new String[] { "classpath*:applicationContext.xml", 6 "/daoContext.xml" }; 7 } 8 9 public void testALogin() throws Exception { 10 11 request.setParameter("manager.name", "oracle"); 12 request.setParameter("manager.pass", "oracle"); 13 request.setParameter("vercode", "123456"); 14 15 ActionProxy proxy = getActionProxy("/processLogin"); 16 LoginAction loginAction = (LoginAction) proxy.getAction(); 17 18 // setup httpsession before invoking Action to make it equals to the 19 // vercode code 20 Map<String, Object> httpSession = new HashMap<>(); 21 httpSession.put("rand", "123456"); 22 ServletActionContext.getContext().setSession(httpSession); 23 // inject beans for Action properties before executing Action.execute() 24 EmpManager mgr = (EmpManager) applicationContext.getBean("empManager"); 25 loginAction.setEmpManager(mgr); 26 27 String result = proxy.execute(); 28 assertTrue("result=" + result + "|" 29 + loginAction.getActionMessages().toString(), 30 result.equals("mgr")); 31 // assertTrue(ServletActionContext.getPageContext().getException().getMessage().toString(),result.equals("mgr")); 32 33 } 34 35 public void testPunchAction() throws Exception { 36 EmpManager empMgr = (EmpManager) applicationContext.getBean("empManager"); 37 List<AttendType> types = empMgr.getAllType(); 38 for (AttendType type : types) { 39 System.out.println(type.getId() + "," + type.getAmerce()); 40 } 41 } 42 }
需要注意的是上面的第25行的目的是為Action類中的屬性注入bean, 因為我這里的Action bean並沒有放在Spring容器中托管, 在實際項目中,struts框架會自動裝配Action的屬性, 但在這里需要手工裝配。
另外繼承了StrutsSpringTestCase的測試類,不僅可以測試Action,同時也能測試Spring容器,例如上面的testPunchAction()方法。
