系列文章目录

前言
SpringBoot支持集成Mockito做单元测试,我们在本地做单元测试测试的时候,经常因为环境等问题需要mock掉外部方法(远程调用、DB查询等),在Mock掉的同时,如果也想根据入参条件返回mock结果,需要怎样做呢?
一、本文要点
接前文,我们已经已介绍SringBoot如果做单元测试了,本文介绍单元测试一些常用技巧。
系列文章完整目录
- 禁用某些自动化配置,如mysql的自动装配
- 指定测试的application.properties文件
- 覆盖application.properties中某项配置
二、实战
- 1、 禁用某些自动化配置,如mysql的自动装配;
@Slf4j
@ActiveProfiles("dev")
@ExtendWith(SpringExtension.class)
@SpringBootTest
// 禁用db的自动装配
@EnableAutoConfiguration(exclude = DataSourceAutoConfiguration.class)
class ServiceTest {
@Test
void syncSku() throws Exception {
log.info("disable db.");
}
}
- 2、 指定测试的application.properties文件,即使用src/test/resources目录下的application.properties文件;
@Slf4j
@ActiveProfiles("dev")
@ExtendWith(SpringExtension.class)
@SpringBootTest
@TestPropertySource(value = "classpath:application.properties")
class ServiceTest {
@Test
void syncSku() throws Exception {
log.info("Specify the application.properties file for testing.");
}
}
- 3、 覆盖application.properties中某项配置;
@Slf4j
@ActiveProfiles("dev")
@ExtendWith(SpringExtension.class)
@SpringBootTest(properties = {"spring.abc.enabled=false"})
class ServiceTest {
@Test
void syncSku() throws Exception {
log.info("disable abc.");
}
}