1. 单独使用JUnit测试Spring应用
Spring整合JUnit之前,我都是直接用JUnit测试Spring应用,每次都要手动创建容器,再从容器中取出Bean1
2
3
4
5
6
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("classpath:applicationContext.xml") // 指定Bean配置文件的路径
(SpringJUnit4ClassRunner.class) // 指定使用Spring的单元测试驱动类
public class SpringTest {
// 可以直接注入
private Person person;
/** 测试方法 */
public void test() {
System.out.println(person);
}
}
3. @ContextConfiguration注解
3.1. 指定Spring Bean配置文件的路径
指定单个Bean配置文件1
2
3
4// 以下3种方式等价
("classpath:applicationContext.xml")
(locations="classpath:applicationContext.xml")
(locations = { "classpath:applicationContext.xml" })
指定多个Bean配置文件1
2(locations = { "classpath:applicationContext1.xml", "classpath:applicationContext2.xml" })
({ "classpath:applicationContext1.xml", "classpath:applicationContext2.xml" })
3. @RunWith注解
@RunWith是JUnit注解,指定用哪种驱动进行单元测试