- JUnit是一個非常好用的測試框架,但在對SSH架構的Java代碼中需要注入由Spring管理的Bean,下面就簡單介紹一下使用JUnit4對SSHSSH2框架Service/Dao層進行單元測試的方法。
- 在建立JUnit Test Case 測試類時,勾選setUpBeforeClass,我們需要在setUpBeforeClass()類中加載Spring配置文件。其它步驟和一般的Java測試過程一樣(添加測試類的名稱,選擇需要測試的類和要測試的方法)。
- 建立好測試類後在setUpBeforeClass() 類中添加ApplicationContext context = new FileSystemXmlApplicationContext(new String[]{"src/applicationContext.xml"});來加載配置文件,注意配置文件的路徑(根據自己的配置文件位置選擇)。然後使用context.getBean()獲取對象。
- 示例:
- public class testService
- {
- public static EnterpriseinfoServiceImpl service;
- @BeforeClass
- public static void setUpBeforeClass() throws Exception
- {
- System.out.println("加載配置文件……");
- ApplicationContext context = new FileSystemXmlApplicationContext(new String[]{"src/applicationContext.xml"});
- System.out.println("加載配置文件成功");
- service = (EnterpriseinfoServiceImpl) context.getBean("enterpriseinfoService"); //enterpriseinfoService爲applicationContext.xml配置文件中Service類對象id值
- }
- @Test
- public void testSave()
- {
- try
- {
- Enterpriseinfo info = new Enterpriseinfo();
- info.setEnglishabbreviation("Myenglishname");
- info.setEnglishfullname("myenglishfullname");
- info.setEnterpriseabbreviation("enterpriseabbreviation");
- info.setEnterprisefullname("enterprisefullname");
- info.setStockcode(12434);
- info.setId(3);
- service.save(info);
- } catch (Exception e)
- {
- e.printStackTrace();
- }
- }
- }
注意:該測試方法測試後數據並不會自動回滾
使用JUnit4對SSH2框架Service/Dao層進行單元測試
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.