JUnit是一套的單元測試框架,而Maven是的Java項目構建和管理工具,兩者結合可以很方便地對項目進行自動化測試。
一般的簡單Java應用不多說了,一些框架會提供針對junit的擴展,使得測試變得更容易,例如Spring官方提供了spring-test,用于提供獲取ApplicationContext等方面的支持。
首先要做的是,改變JUnit的實際執(zhí)行類,將默認的執(zhí)行類Suite替換為Spring提供的SpringJUnit4ClassRunner,也是在測試類前面加上一個注解:
@RunWith(SpringJUnit4ClassRunner.class)
然后,我們需要告訴這個測試類Spring配置文件的位置:
@ContextConfiguration(locations={"classpath:applicationContext.xml",
"classpath:applicationContext-security.xml","file:src/main/webapp/WEB-INF/servlet.xml"})
筆者這里展示了兩種配置文件路徑的寫法。前兩個是spring常見的配置文件,放在classpath根目錄下,而“file”開頭的路徑是完全限定路徑,默認是相對于實際的項目路徑的,例如筆者使用Eclipse進行開發(fā),這個路徑的寫法是相對于項目文件所在文件夾的根目錄的。該寫法適用于沒有直接放在classpath下的一些web相關的配置文件,例如本例展示的是放在常見的WEB-INF目錄下的一個文件。
基于以上描述,筆者寫了一個Spring測試基類:
package com.test.basic;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={/*"file:src/main/webapp/WEB-INF/wxiot-servlet.xml",*/ "classpath:applicationContext.xml",
"classpath:applicationContext-security.xml"})
public classTestBase {
protected Log logger = LogFactory.getLog(TestBase.class);
@Before
//一些公用的“初始化”代碼
public void before(){
}
}