主要步驟
1. 在工程的pom文件中增加spring-test的依賴:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
2. 使用springframework提供的單元測(cè)試
新建測(cè)試類,并在該類上加上兩個(gè)注解:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath*:ApplicationContext.xml"})
@RunWith 大家并不陌生,junit4里用它來(lái)做junit加載器
@ContextConfiguration 主要用來(lái)加載spring的配置文件路徑:是一個(gè)字符串?dāng)?shù)組,可以加載多個(gè)spring配置文件
測(cè)試代碼如下:
1 import static org.junit.Assert.assertEquals;
2
3 import org.junit.Test;
4 import org.junit.runner.RunWith;
5 import org.springframework.beans.factory.annotation.Autowired;
6 import org.springframework.context.ApplicationContext;
7 import org.springframework.test.context.ContextConfiguration;
8 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
9
10 @RunWith(SpringJUnit4ClassRunner.class)
11 @ContextConfiguration(locations = {"classpath:ApplicationContext.xml"})
12 public class EmpolyeeTest {
13 @Autowired
14 ApplicationContext ctx;
15
16 @Test
17 public void testEmployee(){
18 Employee employee =(Employee) ctx.getBean("employee");
19 assertEquals("zhangsan",employee.getName());
20 }
21
22 }
3. 封裝基于AbstractJUnit4SpringContextTests的測(cè)試基類
1 import org.junit.Test;
2 import org.junit.runner.RunWith;
3 import org.springframework.context.ApplicationContext;
4 import org.springframework.test.context.ContextConfiguration;
5 import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
6 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
7
8 @RunWith(SpringJUnit4ClassRunner.class)
9 @ContextConfiguration(locations={"classpath*:ApplicationContext.xml"})
10 public class SpringTest extends AbstractJUnit4SpringContextTests {
11
12
13 public <T> T getBean(Class<T> type){
14 return applicationContext.getBean(type);
15 }
16
17 public Object getBean(String beanName){
18 return applicationContext.getBean(beanName);
19 }
20 protected ApplicationContext getContext(){
21 return applicationContext;
22 }
然后其他測(cè)試類只需要繼承該類即可,可以省去每次都要綁定Application對(duì)象。
4. 當(dāng)項(xiàng)目變得復(fù)雜,其中的spring配置文件被拆分成了多個(gè),這樣該如何引入多個(gè)配置文件呢?如下:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath*:spring-ctx-service.xml", "classpath*:spring-ctx-dao.xml" })
這樣可以輕松的引入多個(gè)spring的配置文件了;蛘吲渲梅夏骋粋(gè)正則表達(dá)式的一類文件,如:
1 @RunWith(SpringJUnit4ClassRunner.class)
2 @ContextConfiguration(locations = "classpath*:spring-ctx-*.xml")