JUnit是一套的單元測(cè)試框架,而Maven是的Java項(xiàng)目構(gòu)建和管理工具,兩者結(jié)合可以很方便地對(duì)項(xiàng)目進(jìn)行自動(dòng)化測(cè)試。
一般的簡(jiǎn)單Java應(yīng)用不多說(shuō)了,一些框架會(huì)提供針對(duì)junit的擴(kuò)展,使得測(cè)試變得更容易,例如Spring官方提供了spring-test,用于提供獲取ApplicationContext等方面的支持。
首先要做的是,改變JUnit的實(shí)際執(zhí)行類,將默認(rèn)的執(zhí)行類Suite替換為Spring提供的SpringJUnit4ClassRunner,也是在測(cè)試類前面加上一個(gè)注解:
@RunWith(SpringJUnit4ClassRunner.class)
然后,我們需要告訴這個(gè)測(cè)試類Spring配置文件的位置:
@ContextConfiguration(locations={"classpath:applicationContext.xml",
"classpath:applicationContext-security.xml","file:src/main/webapp/WEB-INF/servlet.xml"})
筆者這里展示了兩種配置文件路徑的寫(xiě)法。前兩個(gè)是spring常見(jiàn)的配置文件,放在classpath根目錄下,而“file”開(kāi)頭的路徑是完全限定路徑,默認(rèn)是相對(duì)于實(shí)際的項(xiàng)目路徑的,例如筆者使用Eclipse進(jìn)行開(kāi)發(fā),這個(gè)路徑的寫(xiě)法是相對(duì)于項(xiàng)目文件所在文件夾的根目錄的。該寫(xiě)法適用于沒(méi)有直接放在classpath下的一些web相關(guān)的配置文件,例如本例展示的是放在常見(jiàn)的WEB-INF目錄下的一個(gè)文件。
基于以上描述,筆者寫(xiě)了一個(gè)Spring測(cè)試基類:
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(){
}
}