Spring学习4:Spring集成Junit

前言

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());
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值