译:在 Docker 中运行 Spring Boot 的高级功能测试

本贴最后更新于 2008 天前,其中的信息可能已经斗转星移

译:在 Docker 中运行 Spring Boot 的高级功能测试

原文链接:https://dzone.com/articles/advanced-functional-testing-in-spring-boot-by-usin

作者:Taras Danylchuk

译者:liumapp

想要学习更多有关 Spring Boot 项目的功能测试吗?阅读这篇博客可以让您掌握如何利用 Docker 容器进行测试。

概览

本文重点介绍如何使用 Spring Boot 进行功能测试的一些最佳实践。我们将演示如何在不设置模拟环境的情况下将服务作为黑盒测试的高级方法。

本文是我之前这篇文章 Native Integration Testing in Spring Boot 的后续。

因此我将参考上一篇文章来介绍这两种测试方法的区别。

我建议你在阅读这篇文章之前先了解上一篇文章。

理论

让我们从功能测试的定义开始(来自于 Techopedia):

功能测试是在软件开发过程中使用的软件测试流程,通过测试来确保软件符合所有的预期需求。 功能测试也是一种检查软件的方法,通过这种方法来确保它具有指定的所有必须功能。

虽然这个解释看起来有点让人迷惑,但不需要担心——接下来的定义提供了更进一步的解释(来自于 Techopedia):

功能测试主要用于验证一个软件是否提供最终用户或业务所需要的输出。 通常,功能测试涉及评估和比较每个软件功能与业务需求。
通过向软件提供一些相关输入进行测试,以便评估软件的输出并查看其与基本要求相比是符合、关联还是变化的。
此外,功能测试还可以检查软件的可用性,例如确保导航功能能够按要求工作。
在我们的例子中,我们将微服务作为一个软件,这个软件将根据最终用户的要求来提供一些输出。

目的

功能测试应涵盖我们应用程序的以下方面:

  • 上下文启动 - 这可确保服务在上下文中没有冲突,并且可以在没有问题的情况下进行初始化。

  • 业务需求/用户故事 - 包括所请求的功能。

基本上,每个(或大多数)用户的故事都应该有自己的专用功能测试。

我们不需要编写上下文启动测试,因为只要有一个功能要测试,那么上下文启动无论如何都会被测试到的。

实践

为了演示如何使用我们的最佳实践,我们需要编写一些示范服务代码。

就让我们从头开始吧。

任务

我们的新服务有以下要求:

  • 用于存储和检索用户详细信息的 REST API。

  • 通过 REST 检索联系服务中的联系人详细信息,从而检索用户详细信息的 REST API。

架构设计

对于此任务,我们将基于 Spring 平台作为框架,使用 Spring Boot 作为应用的启动者。

为了存储用户详细信息,我们将使用 MariaDB 数据库。

由于服务应存储和检索用户详细信息,因此将其命名为用户详细信息服务是合乎逻辑的。

在实现之前,应该使用组件图来更好地理解系统的主要组件:

1.pic.jpg

实现

以下示例代码包含许多 Lombok 注释。

您可以在网站上的 docs 文件中找到每个注释的说明。

模型

用户详情模型:

@Value(staticConstructor = "of")
public class UserDetails {
 String firstName; String lastName; public static UserDetails fromEntity(UserDetailsEntity entity) { return UserDetails.of(entity.getFirstName(), entity.getLastName()); } public UserDetailsEntity toEntity(long userId) { return new UserDetailsEntity(userId, firstName, lastName); }}

用户联系人模型:

@Value
public class UserContacts {
 String email; String phone;}

具有汇总信息的用户类:

@Value(staticConstructor = "of")
public class User {
 UserDetails userDetails; UserContacts userContacts;}

REST API

@RestController
@RequestMapping("user")
@AllArgsConstructor
public class UserController {
 private final UserService userService; @GetMapping("/{userId}") //1 public User getUser(@PathVariable("userId") long userId) { return userService.getUser(userId); } @PostMapping("/{userId}/details") //2 public void saveUserDetails(@PathVariable("userId") long userId, @RequestBody UserDetails userDetails) { userService.saveDetails(userId, userDetails); } @GetMapping("/{userId}/details") //3 public UserDetails getUserDetails(@PathVariable("userId") long userId) { return userService.getDetails(userId); }}
  1. 按 ID 获取用户汇总数据

  2. 按 ID 保存用户的用户详细信息

  3. 按 ID 获取用户详细信息

客户联系人服务

@Component
public class ContactsServiceClient {
 private final RestTemplate restTemplate; private final String contactsServiceUrl; public ContactsServiceClient(final RestTemplateBuilder restTemplateBuilder, @Value("${contacts.service.url}") final String contactsServiceUrl) { this.restTemplate = restTemplateBuilder.build(); this.contactsServiceUrl = contactsServiceUrl; } public UserContacts getUserContacts(long userId) { URI uri = UriComponentsBuilder.fromHttpUrl(contactsServiceUrl + "/contacts") .queryParam("userId", userId).build().toUri(); return restTemplate.getForObject(uri, UserContacts.class); }}

详细信息实体及其存储库

@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
public class UserDetailsEntity {
 @Id private Long id; @Column private String firstName; @Column private String lastName;}
@Repository
public interface UserDetailsRepository extends JpaRepository {
}

用户服务

@Service
@AllArgsConstructor
public class UserService {
 private final UserDetailsRepository userDetailsRepository; private final ContactsServiceClient contactsServiceClient; public User getUser(long userId) { UserDetailsEntity userDetailsEntity = userDetailsRepository.getOne(userId); //1 UserDetails userDetails = UserDetails.fromEntity(userDetailsEntity); UserContacts userContacts = contactsServiceClient.getUserContacts(userId); //2 return User.of(userDetails, userContacts); //3 } public void saveDetails(long userId, UserDetails userDetails) { UserDetailsEntity entity = userDetails.toEntity(userId); userDetailsRepository.save(entity); } public UserDetails getDetails(long userId) { UserDetailsEntity userDetailsEntity = userDetailsRepository.getOne(userId); return UserDetails.fromEntity(userDetailsEntity); }}
  1. 从 DB 检索用户详细信息

  2. 从联系人服务中检索用户联系人

  3. 返回具有汇总数据的用户

应用启动类和它的配置文件

UserDetailsServiceApplication.java


@SpringBootApplication
public class UserDetailsServiceApplication {
 public static void main(String[] args) { SpringApplication.run(UserDetailsServiceApplication.class, args); }}

application.properties:

#contact service
contacts.service.url=http://www.prod.contact.service.com
#database
user.details.db.host=prod.maria.url.com
user.details.db.port=3306
user.details.db.schema=user_details
spring.datasource.url=jdbc:mariadb://${user.details.db.host}:${user.details.db.port}/${user.details.db.schema}
spring.datasource.username=prod-username
spring.datasource.password=prod-password
spring.datasource.driver-class-name=org.mariadb.jdbc.Driver

Mavan 配置文件 pom.xml


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">
 4.0.0 user-details-service 0.0.1-SNAPSHOT jar User details service  com.tdanylchuk functional-tests-best-practices 0.0.1-SNAPSHOT    org.springframework.boot spring-boot-starter-data-jpa   org.springframework.boot spring-boot-starter-web   org.projectlombok lombok provided   org.mariadb.jdbc mariadb-java-client 2.3.0      org.springframework.boot spring-boot-maven-plugin   

注意:父级是自定义的 functional-tests-best-practices 项目,它继承了 spring-boot-starter-parent。稍后将对此进行说明。

目录结构

2.pic.jpg

这几乎是我们为满足初始要求所需要的一切:保存和检索用户详细信息,通过联系人检索的用户详细信息。

功能测试

是时候添加功能测试了!对于 TDD(测试驱动开发)是什么,您需要在具体实现之前阅读本节。

位置

在开始之前,我们需要选择功能测试的位置;

有两个相对合适的地方:

  • 通过一个独立的文件夹放在单元测试下:

    3.pic.jpg

    这是开始添加功能测试最简单,最快速的方法,虽然它有一个很大的缺点:如果你想单独运行单元测试,你需要排除功能测试文件夹。

    那为什么不能每次修改代码时都运行所有测试呢?

    因为功能测试在大多数情况下与单元测试相比具有巨大的执行时间,因此应单独运行以节省开发时间。

  • 做为一个独立项目放置在父项目下:

    4.pic.jpg

    1. 父 POM(聚合项目)

    2. Service 项目

    3. 功能测试项目

    这种方法优于前一种方法 - 我们在服务单元测试中有一个独立的功能测试模块,因此我们可以通过单独运行单元测试或功能测试来轻松验证逻辑。另一方面,这种方法需要一个多模块项目结构,与单模块项目相比,这种结构更加困难。

    您可能已经从 service 的 pom.xml 中猜到,对于我们的情况,我们将选择第二种方法。

父 pom.xml 文件


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">
 4.0.0 com.tdanylchuk functional-tests-best-practices 0.0.1-SNAPSHOT pom Functional tests best practices parent project                                                     org.springframework.boot spring-boot-starter-parent 2.0.4.RELEASE                                                      user-details-service user-details-service-functional-tests   UTF-8 UTF-8 1.8 
  1. spring-boot-starter-parent 是父 POM 的父项目。通过这种方式,我们为 Spring 提供了依赖管理。

  2. 模块声明。注意:顺序很重要,功能测试应始终放置在最后。

案例

对于挑选案例以涵盖功能测试,我们需要考虑两件大事:

  • 功能需求 - 基本上,每个需求都应有自己的功能测试。

  • 执行时间长 - 案例应该侧重于应用程序的关键部分,这与单元测试相反的是它还要涵盖每个次要案例。否则,构建时间将是巨大的。

构建

是的,测试还需要考虑构建文件,尤其是那些受执行时间影响程度比较大的功能测试,比如一些业务逻辑可能会随着时间的推移变得过于复杂。

此外,功能测试应该是可维护的。这意味着,在功能转换的情况下,功能测试对开发人员来说不是一件令人头疼的问题。

步骤

步骤(也称为固定节点)是一种封装每个通信通道逻辑的方法。

每个通道都应有自己的步骤对象,与其他步骤隔离。

在我们的例子中,我们有两个通信渠道:

  • 用户详细信息服务的 REST API(输入频道)

  • 联系人服务的 REST API(输出频道)

对于输入频道的 REST,我们将使用名为 REST Assured 的库。

与我们之前使用 MockMvc 进行验证 REST API 的集成测试相比,这里我们使用更多的黑盒测试来避免测试模拟对象破坏 Spring 的上下文。

至于 REST 输出频道,我们将使用 WireMock。

我们不会让 Spring 用 REST 模板替换模拟的模板。

相反,WireMock 引擎使用的 jetty 服务器将与我们的服务一起启动,以模拟真正的外部 REST 服务。

用户详情步骤


@Component
public class UserDetailsServiceSteps implements ApplicationListener {
 private int servicePort; public String getUser(long userId) { return given().port(servicePort) .when().get("user/" + userId) .then().statusCode(200).contentType(ContentType.JSON).extract().asString(); } public void saveUserDetails(long userId, String body) { given().port(servicePort).body(body).contentType(ContentType.JSON) .when().post("user/" + userId + "/details") .then().statusCode(200); } public String getUserDetails(long userId) { return given().port(servicePort) .when().get("user/" + userId + "/details") .then().statusCode(200).contentType(ContentType.JSON).extract().asString(); } @Override public void onApplicationEvent(@NotNull WebServerInitializedEvent webServerInitializedEvent) { this.servicePort = webServerInitializedEvent.getWebServer().getPort(); }}

就像你从 steps 对象中看到的,每个 API 都有自己的方法。

默认情况下,REST Assured 将访问 localhost 的 API,但需要指定端口号否则我们的服务将使用随机端口来启动。

为了区分端口号,我们应该从 WebServerInitializedEvent 中去获取端口。

注意:@LocalServerPort 注解不能在此处使用,因为在 Spring Boot-embedded 容器启动之前就初始化了步骤的 bean。

联系人服务步骤

@Component
public class ContactsServiceSteps {
 public void expectGetUserContacts(long userId, String body) { stubFor(get(urlPathMatching("/contacts")).withQueryParam("userId", equalTo(String.valueOf(userId))) .willReturn(okJson(body))); }}

在这里,我们需要以与从我们的应用程序调用远程服务时相同的方式来模拟服务器的端口、参数等。

数据库

我们的服务是将数据存储在 Maria DB 中,但就功能测试而言,数据的存储位置并不重要,因此按照黑盒测试的要求,我们不需要在测试中提及数据库。

假设在未来,我们考虑将 Maria DB 更改为某些 NoSQL 解决方案,那么功能测试应不需要做出改动。

那么,为此解决方案是什么?

当然,我们可以使用嵌入式解决方案,就像在集成测试中使用 H2 数据库一样,但在生产时,我们的服务又将使用 Maria DB,这可能会导致某些地方出错。

例如,我们有一个名为 MAXVALUE 的列,并针对 H2 运行测试,一切正常。但是,在生产中,服务失败了,因为这是 MariaDB 中的一个预留关键字,这意味着我们的测试不如预期的那么好,并且在将服务发布之前可能浪费大量时间来解决这个问题。

避免这种情况的唯一方法是在测试中使用真正的 Maria DB。同时,我们需要确保我们的测试可以在本地执行,而无需设置 Maria DB 的任何其他临时环境。

为了解决这个问题,我们使用 testcontainers 项目,该项目提供常见的轻量级数据库实例:可以在 Selenium Web 浏览器或 Docker 容器中运行的。

但 testcontainers 库不支持 Spring Boot 的开箱即用。因此,我们将使用另一个名为 testcontainers-spring-boot 的库,而不是为 MariaDB 编写自定义的 Generic Container 并将其注入 Spring Boot。testcontainers-spring-boot 支持最常用的技术,并可以直接在您的服务中使用:MariaDB,Couchbase,Kafka,Aerospike,MemSQL,Redis,neo4j,Zookeeper,PostgreSQL,ElasticSearch 等等。

要将真正的 Maria DB 注入我们的测试,我们只需要将相应的依赖项添加到我们的 user-details-service-functional-tests 项目 pom.xml 文件中,如下所示:


 com.playtika.testcontainers embedded-mariadb 1.9 test

如果您的服务不使用 Spring Cloud,则应把下述依赖跟上述依赖一并添加:


 org.springframework.cloud spring-cloud-context 2.0.1.RELEASE test

它需要在 Spring Boot 上下文启动之前为 dockerized 资源进行引导。

这种方法显然有很多优点。

由于我们拥有“真实”资源,因此如果无法对所需资源进行真正的连接测试,则无需在代码中编写解决办法。

不幸的是,这个解决方案带来了一个巨大的缺点 - 测试只能在安装 Docker 的环境中运行。

这意味着您的工作站和 CI 工具应该安装 Docker。

此外,您应该准备好更多的时间来执行您的测试。

父测试类

因为执行时间很重要,所以我们需要避免对每个测试进行多个上下文加载,因此 Docker 容器将对所有测试仅启动一次。

Spring 默认启用了上下文缓存功能,但我们需要小心使用:通过添加简单的 @MockBean 注解,我们将强制 Spring 为模拟的 bean 创建一个新的上下文而不是重用现有的上下文。

此问题的解决方案是创建单个父抽象类,该类将包含所有需要的 Spring 注解,以确保所有测试套件重用单个上下文:

@RunWith(SpringRunner.class)
@SpringBootTest(
 classes = UserDetailsServiceApplication.class,               //1 webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)  //2@ActiveProfiles("test")                                              //3
public abstract class BaseFunctionalTest {
 @Rule public WireMockRule contactsServiceMock = new WireMockRule(options().port(8777)); //4 @Autowired                                                       //5 protected UserDetailsServiceSteps userDetailsServiceSteps; @Autowired protected ContactsServiceSteps contactsServiceSteps; @TestConfiguration                                               //6 @ComponentScan("com.tdanylchuk.user.details.steps") public static class StepsConfiguration { }}
  1. 指定 Spring Boot 的测试注解以加载我们服务的主要配置类。

  2. 引导使用 Web 生产环境(默认情况下将使用模拟的环境)。

  3. 测试环境的配置项被加载在了 application-test.properties 文件中,其中包含了一些生产环境的属性,例如 URL,用户,密码等。

  4. WireMockRulet 通过启动 jetty 服务器以便在提供的端口上进行连接。

  5. 步骤是自动加载为 protected 属性的,这样每一个步骤会在每一个测试得到访问。

  6. @TestConfiguration 注解会通过扫描包名来加载上下文的步骤。

在这里,我们试图不修改上下文,这样的好处时在后期用于生产环境时,只需要往上下文添加一些 util 项就可以了,例如步骤和属性覆盖。

使用 @MockBean 注解是不好的做法,因为它会用 mock 替换部分应用程序,所以这部分程序将是没有经过测试的。

在不可避免的情况下 - 例如在业务中获取当前时间 System.currentTimeMillis(),这样的代码应该被重构,最好使用 Clock 对象:clock.millis()。并且,在功能测试中,应该模拟 Clock 对象以便验证结果。

测试属性

application-test.properties:

#contact service                                          #1
contacts.service.url=http://localhost:8777
#database                                                 #2
user.details.db.host=${embedded.mariadb.host}
user.details.db.port=${embedded.mariadb.port}
user.details.db.schema=${embedded.mariadb.schema}
spring.datasource.username=${embedded.mariadb.user}
spring.datasource.password=${embedded.mariadb.password}
 #3spring.jpa.hibernate.ddl-auto=create-drop
  1. 使用 WireMock jetty 服务器节点而不是生产环境下的联系人服务 URL。

  2. 数据库属性的重载。注意:这些属性由 spring-boo-test-containers 库提供。

  3. 在测试中,数据库的表将由 Hibernate 创建。

自我测试

为了进行这项测试,我们做了很多准备工作,让我们先瞅一眼:

public class RestUserDetailsTest extends BaseFunctionalTest {
 private static final long USER_ID = 32343L; private final String userContactsResponse = readFile("json/user-contacts.json"); private final String userDetails = readFile("json/user-details.json"); private final String expectedUserResponse = readFile("json/user.json"); @Test public void shouldSaveUserDetailsAndRetrieveUser() throws Exception { //when userDetailsServiceSteps.saveUserDetails(USER_ID, userDetails); //and contactsServiceSteps.expectGetUserContacts(USER_ID, userContactsResponse); //then String actualUserResponse = userDetailsServiceSteps.getUser(USER_ID); //expect JSONAssert.assertEquals(expectedUserResponse, actualUserResponse, false); }}

在以前,打桩和断言都是通过 JSON 文件来创建使用的。这种方式,把请求和响应的格式同时进行了验证。但在功能测试里,我们最好不要使用确定格式的测试数据,而是使用生产环境中请求/响应数据的副本。

由于整个逻辑封装在步骤、配置和 JSON 文件中,如果改动与功能无关,那么测试将保持不变。例如:

  • 响应数据格式的更改 - 只应修改 JSON 测试文件。

  • 联系人服务节点更改 - 应修改 ContactsServiceSteps 对象。

  • Maria DB 替换为 No SQL DB - 应修改 pom.xml 和 test properties 文件。

功能测试项目的 POM 文件


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">
 4.0.0 user-details-service-functional-tests 0.0.1-SNAPSHOT User details service functional tests  com.tdanylchuk functional-tests-best-practices 0.0.1-SNAPSHOT                                          com.tdanylchuk user-details-service ${project.version} test   org.springframework.boot spring-boot-starter-test test   org.springframework.cloud spring-cloud-context 2.0.1.RELEASE test   com.playtika.testcontainers embedded-mariadb 1.9 test   com.github.tomakehurst wiremock 2.18.0 test   io.rest-assured rest-assured test  

用户详细信息服务作为依赖项添加,因此它可以由 SpringBootTest 进行加载。

目录结构

5.pic.jpg

总而言之,我们有了下一个项目的目录结构。

向服务添加功能不会改变当前目录结构,只会扩展它。

通过添加额外的步骤,比如添加了更多的通信渠道,那么 utils 文件夹下可以添加很多常用方法;

比如带有测试数据的新文件; 当然还有针对每个功能要求的附加测试。

总结

在本文中,我们基于给定的要求构建了一个新的微服务,并通过功能测试来满足这些要求。

在测试中,我们使用黑盒类型的测试,我们尝试不改变应用程序的内部部分,而是作为普通客户端从外部与它进行通信,以尽可能多地模拟生产行为。

同时,我们奠定了功能测试架构的基础,因此未来的服务更改不需要重构现有测试,并且尽可能将添加新的测试简单化。

这个项目的源代码都可以在 GitHub 上找到。

  • B3log

    B3log 是一个开源组织,名字来源于“Bulletin Board Blog”缩写,目标是将独立博客与论坛结合,形成一种新的网络社区体验,详细请看 B3log 构思。目前 B3log 已经开源了多款产品:SymSoloVditor思源笔记

    1083 引用 • 3461 回帖 • 287 关注
  • 测试
    49 引用 • 193 回帖
  • Docker

    Docker 是一个开源的应用容器引擎,让开发者可以打包他们的应用以及依赖包到一个可移植的容器中,然后发布到任何流行的操作系统上。容器完全使用沙箱机制,几乎没有性能开销,可以很容易地在机器和数据中心中运行。

    476 引用 • 899 回帖
  • Spring

    Spring 是一个开源框架,是于 2003 年兴起的一个轻量级的 Java 开发框架,由 Rod Johnson 在其著作《Expert One-On-One J2EE Development and Design》中阐述的部分理念和原型衍生而来。它是为了解决企业应用开发的复杂性而创建的。框架的主要优势之一就是其分层架构,分层架构允许使用者选择使用哪一个组件,同时为 JavaEE 应用程序开发提供集成的框架。

    940 引用 • 1458 回帖 • 159 关注

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...