目录
1.导入Spring集成Junit的坐标
在pom.xml中添加依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
2.使用@Runwith注解替换原来的运行期
@RunWith(SpringJUnit4ClassRunner.class)
3.@ContextConfiguration指定配置文件或配置类
导入配置文件
格式:@ContextConfiguration(“classpath:配置文件名”)
@ContextConfiguration("classpath:applicationContext.xml")//导入xml配置文件
导入配置类
格式:@ContextConfiguration(classes = {类名1.class,类名2.class})
@ContextConfiguration(classes = {SpringConfiguration.class})
4.使用@Autowired注入需要测试的对象
//导入测试对象
@Autowired
private UserService userService;
@Autowired
private DataSource dataSource;
5.创建测试方法进行测试
@Test
public void test() throws SQLException {
userService.save();
System.out.println(dataSource.getConnection());
}
6.完整代码
@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration("classpath:applicationContext.xml")//导入xml配置文件
@ContextConfiguration(classes = {SpringConfiguration.class})//导入配置类
public class SpringJunitTest {
//导入测试对象
@Autowired
private UserService userService;
@Autowired
private DataSource dataSource;
//测试方法
@Test
public void test() throws SQLException {
userService.save();
System.out.println(dataSource.getConnection());
}
}