Spring Boot项目——单元测试
单元测试的作用 / 为什么要进行单元测试
- 首先开发者要知道一点,无论什么情况下,测试一定要做!测试一定要做!测试一定要做!
- 单元测试出现前测试方法
- 启动整个应用,用户通过直接操作页面,操作系统进行测试——每次测试都要启动整个项目
- 写一个测试入口main方法,调用需要测试的方法进行测试——入口一定要记得删除
- 单元测试
- 无论是一个方法,还是单个逻辑,既可以全面测试,又可以化整为零,单元测试
- 代码留存,更改方法后可以复用测试代码,提升效率,同时保存测试记录
系统环境
- Spring Boot 2.2.1RELEASE
- Java 8
- Junit 5
- Maven 3
pom依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <version>2.2.1.RELEASE</version> <scope>test</scope> </dependency>
Controller层测试代码
@ExtendWith(SpringExtension.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @ActiveProfiles(value = "dev") public class HttpRequestTest { @LocalServerPort private int port; @Autowired private TestRestTemplate restTemplate; @Test @Rollback(value="false") public void testHello() { String requestResult = this.restTemplate.getForObject("http://127.0.0.1:" + port + "/test/hellp", String.class); Assertions.assertThat(requestResult).contains("Hello, spring"); } }
- @ExtendWith(SpringExtension.class):让JUnit运行Spring的测试环境,获得Spring环境的上下文的支持。
- @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 、@LocalServerPort:使用本地的一个随机端口启动服务。
- @ActiveProfiles(value="dev"):多环境下使用的测试环境。
- TestRestTemplate:在配置了 webEnvironment 后,Spring Boot 会自动提供一个 TestRestTemplate 实例,可用于发送 HTTP 请求。
- @Rollback:事务是否回滚。
Service层测试代码
@ExtendWith(SpringExtension.class) @SpringBootTest @ActiveProfiles(value = "dev") public class HttpRequestTest { @Test @Rollback(value="false") public void testHello() { DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd"); LocalDate start = LocalDate.parse("2020-10-26", dtf); LocalDate end = LocalDate.parse("2020-10-31", dtf); Integer integer = XXXService.ConflictTime("10000001", start, end); Assert.assertThat(integer, Matchers.notNullValue()); } }
分类:
Spring Boot
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
2017-09-21 Eclipse配置——使用maven命令安装第三方jar包