[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-poJoD63U-1619626601017)(https://i.loli.net/2021/04/21/CywjlKU7vbfcA4V.png)]
经过前面几次文章的分享的UT的相关知识,今天接着分享UT相关最后一测文章,希望对大家在UT的学习中有一点点的帮助。
Spring集成测试
有时候我们需要在跑起来的Spring环境中验证,Spring 框架提供了一个专门的测试模块(spring-test),用于应用程序的集成测试。
在 Spring Boot 中,你可以通过spring-boot-starter-test启动器快速开启和使用它。
这时首先就有了Spring容器运行环境,就可以模拟浏览器调用等操作
引入测试坐标
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.19.0</version>
<scope>test</scope>
</dependency>
为了与生产环境配置区分开
新建一个application-test.yml
server:
port: 8088
spring:
application:
name: hello-service-for-test
controller类,也就是被测对象
@RestController
public class HelloController {
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String hello() throws Exception {
return "Hello World";
}
}
测试方案一
通过TestRestTemplate模拟调用Rest接口
@ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles("test")
class HelloControllerTest {
@Autowired
private TestRestTemplat