SpringBoot使用@RunWith(Parameterized.class)进行参数化测试同时支持依赖注入,以及CommandLineRunner在单元测试时不执行主进程

问题提出

在使用SpringBoot进行单元测试的时候,我发现了两个问题

  1. 使用参数化测试的时候,必须使用 @RunWith(Parameterized.class),而对Spring进行单元测试时,如果想使用依赖注入,即使用 @Autowired 注解,需要使用 @RunWith(SpringRunner.class) 。两个不能同时使用。
  2. 如果 SpringBootApplication 在启动时执行一个 CommandLineRunner,那么在启动单元测试的时候,会立即执行该Runner,但是我只想执行我的单元测试,并不想让整个程序都启动起来。

解决方案

我查了一下资料,发现相关的文章很少,Google了一下发现一篇文章 写JUnit时既用Parameterized又用@Autowired出现无法成功自动注入的解决办法 有提到相关的问题,但是这篇文章在关键位置排版太乱,看不清楚。于是自己尝试着处理了一下。

一、Parameterized和SpringRunner

只使用 @RunWith(Parameterized.class),跟普通的参数化测试一样。然后在测试类中添加以下几行代码,就可以使用依赖注入了。

    @Before
    public void setUp() throws Exception {
        TestContextManager testContextManager = new TestContextManager(getClass());
        testContextManager.prepareTestInstance(this);
    }

二、单元测试启动时不执行 CommandLineRunner

我的程序需要在启动之后需要执行一个阻塞的方法。但是单元测试启动的时候,会先启动SpringBootApplication,于是我的阻塞方法就被调用了,然后进程就被阻塞,永远到达不了我的测试方法,单元测试就无法进行了。

@Component
public class BlockingMethodRunner implements CommandLineRunner {
    /**
     * 在程序启动之后执行某个阻塞的方法
     */
    @Override
    public void run(String... args) throws Exception {
        while(true){
        		System.out.println("this is a blocking method");
        		Thread.sleep(1000);
        }
    }
}

我的思路是使用Spring的@Profile注解,该注解用于指定当前 Bean 只在某个 profile 被激活,即在配置项 spring.profiles.active 中指定激活的情况下,才会加载这个Bean。

@Component
// ! 代表取反,即只有在非unittest的情况下才会加载这个Bean
@Profile("!unittest")
public class BlockingMethodRunner implements CommandLineRunner {
    /**
     * 在程序启动之后执行某个阻塞的方法
     */
    @Override
    public void run(String... args) throws Exception {
        while(true){
        		System.out.println("this is a blocking method");
        		Thread.sleep(1000);
        }
    }
}

当然,我们要在单元测试的resources目录下的application.properties文件中添加这个配置:
spring.profiles.active=unittest

其实@Profile是使用了从Spring的条件化配置Bean 的特性完成的,使用 @Conditional 注解你可以自由决定是否加载当前Bean。

SpringBoot提供了很多常用的Condition,你能想到能用到的各种情况,它几乎都已经考虑到了,你只要选择一个适合你的就可以。

在这里插入图片描述

例如,我们可以使用 @ConditionalOnProperty 指定当某个配置项存在并且等于某个指定的值时,才加载这个Bean.

@Component
// 只有在配置 project.runBlockingMethod 为 true 时才加载这个Bean
@ConditionalOnProperty(name = "project.runBlockingMethod", havingValue = "true")
public class BlockingMethodRunner implements CommandLineRunner {
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值