场景
给springcloud项目写单元测试,执行单元测试还要注册服务等过程,太过繁琐且没意义,因此需要配置忽略。某些自动配置类比如RedisAutoConfiguration等也不需要自动注入
基类
写了如下基类,之后的单元测试继承该类即可
@RunWith(SpringRunner.class)
@ActiveProfiles(value = "junit")
@SpringBootTest(classes = KshptApp.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@Rollback(value = true)
@TestPropertySource(properties={
"spring.autoconfigure.exclude=" +
"org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration," +
"org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration"
})
public class BaseTest {
}
@ActiveProfiles(value = "junit")
定义了一个只用于单元测试的配置文件
忽略注册中心
在我们定义的**application-junit.yml(bootstrap-junit.yml)**中配置
eureka:
client:
enabled: false
则忽略注册中心
忽略配置中心
如果模块使用到配置中心,我们将配置中心的配置项迁移到**application-junit.yml(bootstrap-junit.yml)**中,并配置
spring:
cloud:
config:
enabled: false
则忽略配置中心
其他
比如忽略spring-session,则配置
spring:
session:
store-type: none
排除redis配置类
@TestPropertySource(properties={
"spring.autoconfigure.exclude=" +
"org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration," +
"org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration"
})
基类上该配置就是排除了RedisAutoConfiguration和RedisRepositoriesAutoConfiguration,避免单元测试时因连不到redis而报错