前言
Spring集成Junit的原因:
因为每次测试都要加载容器和实例化Bean,使测试变的繁琐
解决办法 :
让SpringJunit负责创建Spring容器,但是需要将配置文件告诉它(applicationContext.xml), 将需要进行测试Bean直接在测试类进行注入
步骤
1.导入spring继承Junit坐标
在pom.xml里配置如下
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.13.RELEASE</version>
</dependency>
2.使用@Runwith注解替换原来的运行期
用@RunWith运行Spring提供的内核SpringJUnitClassRuner.class,它帮我们进行测试
import org.junit.runner.RunWith;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
//使用Spring提供的内核进行测试
@RunWith(SpringJUnit4ClassRunner.class)
3.使用@ContextConfiguration指定配置文件或配置类
- 加载核心配置文件方法,里面有一些必要的组件,比如说扫描组件
import org.springframework.test.context.ContextConfiguration;
@ContextConfiguration("classpath:applicationContext.xml")
- 加载核心配置类方法,注意classes是个数组
import com.boo.config.SpringConfiguration;
import org.springframework.test.context.ContextConfiguration;
@ContextConfiguration(classes = {SpringConfiguration.class})
4.使用@Autowired注入需要测试的对象
public class SpringJunitTest {
@Autowired
private UserService userService;
@Autowired
private DataSource dataSource;
}
5.创建测试方法进行测试
@Test
public void test1() throws SQLException {
userService.save();
System.out.println(dataSource.getConnection());
}
----测试结果-----
save...
com.mysql.jdbc.Driver
完整代码和截图
package com.boo.test;
import com.boo.config.SpringConfiguration;
import com.boo.serviece.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.sql.DataSource;
import java.sql.SQLException;
//使用Spring提供的内核进行测试
@RunWith(SpringJUnit4ClassRunner.class)
//加载核心配置文件,里面有一些必要的组件,比如说扫描组件
//@ContextConfiguration("classpath:applicationContext.xml")
//加载核心配置类
@ContextConfiguration(classes = {SpringConfiguration.class})
public class SpringJunitTest {
@Autowired
private UserService userService;
@Autowired
private DataSource dataSource;
@Test
public void test1() throws SQLException {
userService.save();
System.out.println(dataSource.getConnection());
}
}