提高单元测试的运行速度

提高单元测试的运行速度

框架:springboot2.7.9,Junit5
通常在单元测试时,运行一次需要很长的时间加载上下文,可能你只需要测试一个类或者一个包,但是容器启动加载了整个项目,耗时较长

如何加快测试速度

测试时只加载自己需要的类或者包

只加载某个类

package com.example.demo;

import com.example.demo.service.HelloService;
import com.example.demo.service.impl.HelloServiceImpl;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;

@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = {HelloServiceImpl.class})
class DemoApplicationTests {

    @Autowired
    private HelloService helloService;

    @Test
    void contextLoads() {

        helloService.hello();
    }

}

只加载某个包

如果只想加载service包下的类

创建一个配置类ServiceConfig.class

package com.example.demo;

import com.example.demo.service.LockService;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.FilterType;

@TestConfiguration
@ComponentScan(basePackages = "com.example.demo.service")
public class ServiceConfig {
}

使用@ContextConfiguration加载指定的配置类,就会将service包下所有类加载到上下文中
注意:@ExtendWith(SpringExtension.class)是springboot2.x和Junit5中的,如果是Junit4,使用@RunWith(SpringRunner.class)

package com.example.demo;

import com.example.demo.service.HelloService;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;

@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = ServiceAutoConfig.class)
class DemoApplicationTests {

    @Autowired
    private HelloService helloService;

    @Test
    void contextLoads() {

        helloService.hello();
    }

}

加载包下的有些类不想被加载,可以使用Filter来进行过滤

@TestConfiguration
@ComponentScan(basePackages = "com.example.demo.service",
        excludeFilters = {@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = LockService.class)})
public class ServiceConfig {
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值