Spring 整合单元测试

1. 单独使用JUnit测试Spring应用

Spring整合JUnit之前,我都是直接用JUnit测试Spring应用,每次都要手动创建容器,再从容器中取出Bean

1
2
3
4
5
6
@Test
public void test() throws Exception {
ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");
Person person = (Person) ioc.getBean("person");
System.out.println(person);
}

后来才看到,原来Spring整合了JUnit,叫做Spring Test,专门用来测试Spring应用,给测试带来很大的方便

2. Spring 整合JUnit流程

添加依赖

1
2
3
4
5
6
7
8
9
10
11
12
13
<!-- junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>

编写单元测试

1
2
3
4
5
6
7
8
9
10
11
12
@ContextConfiguration("classpath:applicationContext.xml")  // 指定Bean配置文件的路径
@RunWith(SpringJUnit4ClassRunner.class) // 指定使用Spring的单元测试驱动类
public class SpringTest {
@Autowired // 可以直接注入
private Person person;

/** 测试方法 */
@Test
public void test() {
System.out.println(person);
}
}

3. @ContextConfiguration注解

3.1. 指定Spring Bean配置文件的路径

指定单个Bean配置文件

1
2
3
4
// 以下3种方式等价
@ContextConfiguration("classpath:applicationContext.xml")
@ContextConfiguration(locations="classpath:applicationContext.xml")
@ContextConfiguration(locations = { "classpath:applicationContext.xml" })

指定多个Bean配置文件

1
2
@ContextConfiguration(locations = { "classpath:applicationContext1.xml", "classpath:applicationContext2.xml" })
@ContextConfiguration({ "classpath:applicationContext1.xml", "classpath:applicationContext2.xml" })

3. @RunWith注解

@RunWith是JUnit注解,指定用哪种驱动进行单元测试

panchaoxin wechat
关注我的公众号
支持一下