欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > 能源 > SpringCloud2023实战之接口服务测试工具SpringBootTest

SpringCloud2023实战之接口服务测试工具SpringBootTest

2025/5/11 15:47:33 来源:https://blog.csdn.net/sunzroad/article/details/143787393  浏览:    关键词:SpringCloud2023实战之接口服务测试工具SpringBootTest

你好,这里是专栏“SpringCloud2023实战”。

点击查看专栏SpringCloud实战

往期推荐:

  • SpringCloud和SpringBoot的版本依赖该怎么选择
  • SpringCloud2023最新版本该如何进行组件选型?
  • 如何简洁高效的搭建一个SpringCloud2023的maven工程
  • 如何在SpringCloud2023中快速集成注册中心
  • 如何在SpringCloud2023中快速集成配置中心
  • 在SpringCloud2023中快速集成SpringCloudGateway网关
  • 使用Sentinel进行服务调用的熔断和限流管理
  • SpringCloud2023中使用Seata解决分布式事务

前言

Spring Boot Test 是 Spring Boot 生态系统中的一部分,它基于 Spring Test 和 JUnit 等其他测试框架,提供了便捷高效的测试手段。Spring Boot Test 进行了再次封装,增加了切片测试,并增强了 mock 能力。

SpringBootTest是Spring Framework提供的用于编写集成测试的工具类,它可以帮助开发人员轻松地编写自动化的集成测试用例,以验证整个Spring应用程序上下文的行为。SpringBootTest可以加载完整的应用程序上下文,并支持对各个组件进行集成测试,包括控制器、服务、存储库、数据库访问等。

  • 加载应用程序上下文:SpringBootTest能够加载整个Spring应用程序上下文,包括所有的bean定义、配置文件、组件扫描等。这使得测试用例能够在一个真实的Spring环境中执行,而不需要手动模拟或配置大量的依赖项。
  • 自动配置:通过使用SpringBootTest注解,开发人员可以自动配置所需的环境,例如内嵌的数据库、自定义的Bean等。这样可以减少测试用例中的重复代码,提高测试的可维护性。
  • 模拟环境:除了加载完整的应用程序上下文外,SpringBootTest还提供了一些模拟环境的功能,比如可以使用@MockBean来替换某些bean的实际实现,以便更好地控制测试环境。
  • 自动化测试:SpringBootTest支持JUnit或者TestNG等测试框架,可以方便地编写各种类型的自动化测试用例,包括单元测试、集成测试、端到端测试等。
  • 与Spring Boot集成:SpringBootTest天然与Spring Boot集成,可以很容易地对Spring Boot应用程序进行集成测试。

SpringBootTest同时集成了JUnit Jupiter、AssertJ、Hamcrest测试辅助库,使得更容易编写但愿测试代码。

核心组件如下:

  • JUnit 5:Java应用程序单元测试的事实标准。
  • Spring Test和Spring Boot Test:为Spring Boot应用程序提供实用工具和集成测试支持。
  • AssertJ:一个流畅的断言库。
  • Hamcrest:一个匹配器对象库(也称为约束或谓词)。
  • Mockito:一个Java模拟框架。
  • JSONassert:一个针对JSON的断言库。
  • JsonPath:JSON的XPath解析库。

SpringBootTest应用集成

引入pom.xml

  • 引入SpringBootTest主要是引入 spring-boot-starter-test
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><parent><groupId>io.rainforest</groupId><artifactId>banana</artifactId><version>1.0</version></parent><modelVersion>4.0.0</modelVersion><artifactId>banana-client6-test</artifactId><description>spring cloud banana-client6-test</description><packaging>jar</packaging><dependencies><!-- 核心依赖省略 --><!--测试依赖--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><!--测试依赖-便于测试webflux相关的接口--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-webflux</artifactId></dependency></dependencies></project>

修改配置

  • 无特殊修改。
spring.application.name: banana-client5-tracing
server:port: 10120servlet:context-path: /app

修改启动类

  • 启动类不需要特殊修改。
package io.rainforest.banana.app;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}
}

接口demo

  • 通过访问 http://localhost:10120/ 测试接口。
package io.rainforest.banana.app.web.demo;import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;import java.util.ArrayList;
import java.util.List;@RestController
@Slf4j
public class HelloWorld {@GetMapping("/")public String hello(String hello){log.info("this is a test");return "Hello World";}
}

SpringBootTest测试用例编写

Spring Boot应用程序是一个Spring ApplicationContext,因此除了使用Spring context进行测试之外,不需要做任何特别的事情。Spring Boot 提供了一个 @SpringBootTest 注解,当需要 Spring Boot 功能时,它可以作为标准 spring-test @ContextConfiguration 注解的替代。该注解通过 SpringApplication 在测试中创建 ApplicationContext 来工作。除了 @SpringBootTest,还提供了许多其他注解来测试应用程序的更具体部分。

默认情况下,@SpringBootTest不会启动服务器。您可以使用@SpringBootTest的webEnvironment属性来进一步定义测试运行的方式:

  • MOCK(默认值):加载一个Web应用程序上下文并提供模拟的Web环境。在使用此注解时,嵌入式服务器不会启动。如果您的类路径上没有Web环境,则此模式会自动回退到创建常规的非Web应用程序上下文。它可以与@AutoConfigureMockMvc或@AutoConfigureWebTestClient一起使用,用于对您的Web应用程序进行基于模拟的测试。
  • RANDOM_PORT:加载一个WebServer应用程序上下文并提供真实的Web环境。嵌入式服务器会启动并侦听一个随机端口。
  • DEFINED_PORT:加载一个WebServer应用程序上下文并提供真实的Web环境。嵌入式服务器会启动并侦听一个已定义的端口(来自您的application.properties文件)或默认端口8080。
  • NONE:通过使用SpringApplication加载一个应用程序上下文,但不提供任何Web环境(模拟或其他方式)。

带启动参数的单元测试

通过args属性可以指定启动参数。

package io.rainforest.banana.app;import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.test.context.SpringBootTest;import static org.assertj.core.api.Assertions.assertThat;@SpringBootTest(args = "--app.test=one")
class MyApplicationArgumentTests {@Testvoid applicationArgumentsPopulated(@Autowired ApplicationArguments args) {assertThat(args.getOptionNames()).containsOnly("app.test");assertThat(args.getOptionValues("app.test")).containsOnly("one");}}

带mock环境的单元测试

通过mockmvc可以发起rest请求测试本地接口。

package io.rainforest.banana.app;import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.reactive.server.WebTestClient;
import org.springframework.test.web.servlet.MockMvc;import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;@SpringBootTest
@AutoConfigureMockMvc
class MyMockMvcTests {@Testvoid testWithMockMvc(@Autowired MockMvc mvc) throws Exception {mvc.perform(get("/")).andExpect(status().isOk()).andExpect(content().string("Hello World"));}// If Spring WebFlux is on the classpath, you can drive MVC tests with a WebTestClient@Testvoid testWithWebTestClient(@Autowired WebTestClient webClient) {webClient.get().uri("/").exchange().expectStatus().isOk().expectBody(String.class).isEqualTo("Hello World");}}

带运行服务的单元测试

带完整的springboot运行环境的单元测试。

package io.rainforest.banana.app;import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.test.web.reactive.server.WebTestClient;@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
class MyRandomPortWebTestClientTests {@Testvoid exampleTest(@Autowired WebTestClient webClient) {webClient.get().uri("/").exchange().expectStatus().isOk().expectBody(String.class).isEqualTo("Hello World");}}

其它的单元测试

SpringBootTest提供了很多集成的starter测试工具类。例如:

  • Spring GraphQL Tests
  • Data Cassandra Tests
  • Data Couchbase Tests

具体内容可以查看SpringBoot的文档了解。

关于作者

来自全栈程序员nine的探索与实践,持续迭代中。(工作卫星codetrend)

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词