Spring整合JUnit

为什么要Spring整合Junit?

主要是为了简化测试而已。使用注解自动创建全局 IOC 容器对象,代替每个测试方法重复创建IOC容器代码。

注意

Spring5.0 以后 ,要求 JUnit 的版本必须是4.12及以上
JUnit 仅用于单元测试,不能将 JUnit 的测试类配置成 spring bean ,否则该配置将会被打包进入工程中。
 
 

@RunWith注解作用?

指定第三方的运行器,我们使用Spring提供的运行器

@ContextConfiguration注解作用?

指定Spring的配置文件或配置类

 

整合步骤 :

1. 添加 spring-test 的依赖包
<!--
        spring整合junit包:spring-test
          注意:使用这个整个包,要求依赖的junit的包必须是4.12及版本以上
        -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>5.1.8.RELEASE</version>
</dependency>
2. XML 配置的项目中,加载配置文件的方式使用 JUnit
 
3. 在注解配置的项目中,使用纯注解的方式使用 JUnit

 

XML配置文件 

1、使用JUnit的注解@RunWith,让JUnit使用Spring提供的运行器

2、使用Spring提供的注解@ContextConfiguration,使用locations="classpath:applicationContext.xml"指定XML的配置文件(locations的别名是value)

3、给测试类中业务对象使用@Autowired注解

4、在测试类中直接使用业务对象即可

 

@RunWith(SpringJUnit4ClassRunner.class)  //设置启动测试类,目的先走spring的测试类
@ContextConfiguration("classpath:applicationContext.xml")   //根据配置文件applicationContext.xml创建IOC容器
public class AppTest3 {

    @Autowired
    private AccountService accountService;

    @Test
    public  void test(){

        //3.调用业务方法测试
        List<Account> accountList = accountService.findAll();

        //4.遍历输出
        accountList.forEach(System.out::println);
    }
}

注解的方式

除了第2步使用classes=SpringConfig.class指定有注解配置的类对象,其它步骤相同

@RunWith(SpringJUnit4ClassRunner.class)  //设置启动测试类,目的先走spring的测试类
@ContextConfiguration(classes=SpringConfiguration.class )   //根据配置注解类创建IOC容器
public class AppTest2 {

    @Autowired
    private AccountService accountService;

    @Test
    public  void test(){

        //3.调用业务方法测试
        List<Account> accountList = accountService.findAll();

        //4.遍历输出
        accountList.forEach(System.out::println);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值