spring集成TestNG【spring和testng的整合】

項目中用到了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管理的事務中進行,測試完後對數據庫的記錄不會造成任何影響。你對數據庫進行一些操作後,它會自動把數據庫回滾,這樣就保證了你的測試對於環境沒有任何影響

集成代碼如下

[java] view plaincopy
  1. @ContextConfiguration   
  2. (locations={"applicationContext.xml"})  
  3. public class TestUser extends AbstractTestNGSpringContextTests{  
  4.    
  5.  @Autowired  
  6.  UserService userService;  
  7.    
  8.  @Test  
  9.  public void test_save_user(){  
  10.   User user = new User();  
  11.   user .setPassword("123456");  
  12.   user .setSex(1);  
  13.   user .setPartyName("test1");  
  14.   user .setEmail("[email protected]");  
  15.   userService.save(user);  
  16.  }  
  17.    
  18.  @Test  
  19.  public void test_inject_factory(){  
  20.   Assert.assertNotNull(userService);  
  21.  }  
  22. }  

其中最重要的就是@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菜單中進行配置

  MyEclipse配置

 轉載地址: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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章