項目中用到了testNG作爲單元測試工具,至於testNG對比junit有啥好處不太清楚,至少從程序員寫testcase來說似乎和junit 4.x並沒有太大的區別。但是據說和一些測試工具整合的時候比較方便。ok,這不是重點。
Spring專門爲Junit testNG提供了一套測試集成接口類——AbstractSpringContextTests類,對於testNG就是其子類:AbstractTestNGSpringContextTests。Spring和testNG整合後,進行單元測試的時只要test類繼承該類,就可以方便的使用spring注入。實現了spring和testNG的無縫整合,我們可以像寫普通類那樣測試被spring IoC容器所管理的類(否則我們必須在開始執行單元測試前重新加載Spring beanfactory,再用getBean("xxx")的方式獲取IoC容器中類。)
除此以外,對測試類spring beanfactory緩存,使得多個測試類之間可以共享同一個的beanfactory實例,從而減少了重複生成beanfactory,提高了運行效率。
繼承該類的測試用例在spring管理的事務中進行,測試完後對數據庫的記錄不會造成任何影響。你對數據庫進行一些操作後,它會自動把數據庫回滾,這樣就保證了你的測試對於環境沒有任何影響
集成代碼如下
- @ContextConfiguration
- (locations={"applicationContext.xml"})
- public class TestUser extends AbstractTestNGSpringContextTests{
- @Autowired
- UserService userService;
- @Test
- public void test_save_user(){
- User user = new User();
- user .setPassword("123456");
- user .setSex(1);
- user .setPartyName("test1");
- user .setEmail("[email protected]");
- userService.save(user);
- }
- @Test
- public void test_inject_factory(){
- Assert.assertNotNull(userService);
- }
- }
其中最重要的就是@ContextConfiguration。默認的從classpath目錄下讀取applicationContext.xml作爲spring的啓動配置文件(對應ClassPathXmlApplicationContext?)。
等同於(locations={"classpath:applicationContext1.xml"})。因此必須確保spring的配置文件在classpath中。
如果有多個spring配置,用逗號進行分隔(locations={"applicationContext.xml", "/applicationContex_transaction.xml"})
另外一種採用filepath定位spring配置文件(對應FileSystemXmlApplicationContext?).
比如在web項目中將相應的配置文件放到WEB-INF目錄下"file:WebRoot/WEB-INF/config/applicationContext.xml",或者可以指定絕對路徑。
實際問題:
項目中,將配置放在了web-inf/config/目錄下對應的xml文件中,但是又在xml文件中對web-inf/config/properties/目錄下的幾個包括log4j.properties在內的幾個properties文件進行了引用。
如果使用file方式指定spring配置文件位置的話,當加載到xml文件中引用的property文件時就會報文件找不到。因爲僅僅指定採用file方式讀取xml文件,對於對於property文件仍然會去classpath搜索。
解決方法
將Webroot加入到項目的classpath目錄中。
或者更好的做法是指定在運行testNG測試時,將webroot加入到classpath中。
Eclipse中 run/run configuration菜單中進行配置
轉載地址:http://blog.csdn.net/blackchoc/article/details/5711860
TestNG官方地址:
1、首頁:http://testng.org/doc/index.html
2、文檔:http://testng.org/doc/documentation-main.html
3、maven倉庫地址:http://testng.org/doc/maven.html
< dependency > |
< groupId >org.testng</ groupId > |
< artifactId >testng</ artifactId > |
< version >6.1.1</ version > |
< scope >test</ scope > |
</ dependency > |
4、eclipse插件:http://testng.org/doc/eclipse.html