优雅单测-1基于SpringBoot快速单测
2020-06-30 本文已影响0人
uncle_hangzhou
1.单元测试
SpringBoot使用Junit进行单元测试
2.快速上手
2.1 依赖引入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-test</artifactId>
<scope>test</scope>
</dependency>
2.2 增加单测
/**
* SpringBoot Test Demo
* 2020-06-23
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = LiveReportServiceTest.Config.class)
@TestPropertySource("classpath:application-test.properties")
public class LiveReportServiceTest {
@Autowired
ILiveReportWriteService iLiveReportWriteService;
@MockBean
LiveReportMapper liveReportMapper;
@Test
public void updateLiveStatusTest() {
int num = 1;
Assert.assertTrue(num >= 1);
}
@Configuration
static class Config {
@Bean
ILiveReportWriteService iLiveReportWriteService() {
return new LiveReportWriteServiceImpl();
}
}
}
RunWith: junit注解,表示使用spring-test包提供SpringRunner环境运行
TestPropertySource:应用的配置使用哪个
SpringBootTest:SpringBoot单元测试的容器启动相关配置
MockBean:Mockito框架,解耦Dao层和Service
2.3 单测对应实例
@Service
public class LiveReportWriteServiceImpl {
@Autowired
private LiveReportMapper liveReportMapper;
}
2.4 完成
image.png至此SpringBoot环境的单测已经运行成功了
可以看到虽然运行起来了,但是总执行时间需要13秒, 其中单测的方法只运行为来23毫秒, 相当于几乎13秒都在加在环境,这显然时间太久了。
另外单元测试本身是指对软件中的最小可测试单元进行检查和验,目前的环境是直接依赖了springboot全家桶,显然是太过依赖与环境了,那么就要考虑如何优化一下
优化很简单,不要启动SpringBoot整体环境,只依赖SpringCore的核心容器就可以了,优化后同样的单测同样环境用例执行只要1秒,执行单测的效率相比直接启动springboot应用快非常多的:
image.png下一章详细介绍如何只依赖SpringCore快速单测