提高单元测试的运行速度
框架: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 {
}