Spring Cloud Contract 2.2.3 是 Spring Cloud 生态中的合约测试框架,基于 Spring Boot 2.2.x 版本构建

SpringCloud Contract是一个伞形项目,提供解决方案帮助用户成功实现消费者驱动合同(CDC)的方法。它包括SpringCloud Contract Verifier项目,这是一个工具,允许在JVM基础上的应用程序进行消费者驱动合同(CDC)开发。该工具附带了用Groovy或YAML编写的合同定义语言(DSL),并用于生成JSON存根定义、消息路由以及验收测试,以验证服务器侧API实现是否符合合同。

Spring Cloud Contract 2.2.3 核心功能

Spring Cloud Contract 2.2.3 通过定义服务间交互的合约(如 HTTP 请求/响应、消息格式),确保提供者和消费者在独立开发时仍能兼容。支持基于 Groovy 或 YAML 的合约描述,并自动生成测试桩(Stub)和验证逻辑。

关键特性

  • 消费者驱动合约(CDC):消费者定义预期交互,提供者实现后通过合约验证。
  • 多协议支持:覆盖 HTTP/REST 和消息(如 Spring Cloud Stream、Apache Kafka)。
  • 自动生成测试:提供者端生成基于合约的集成测试,消费者端生成 WireMock 桩模块。
  • 与 Spring Boot 2.2.x 深度集成:依赖管理、自动配置与 Spring Boot 生态无缝协作。

典型使用场景

  1. 提供者测试:通过 @AutoConfigureStubRunner 加载合约生成的桩,验证提供者实现是否符合预期。
  2. 消费者测试:消费者端利用 WireMock 桩模拟提供者行为,隔离测试自身逻辑。
  3. 契约存储:合约文件通常存放在 Git 仓库,通过 spring-cloud-contract-gradle-plugin 或 Maven 插件共享。

代码示例(Groovy 合约)

Contract.make {
    request {
        method 'GET'
        url '/api/orders/1'
    }
    response {
        status 200
        body([
            id: 1,
            product: "Spring Cloud Contract Book"
        ])
        headers {
            contentType('application/json')
        }
    }
}

依赖配置(Maven)

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-contract-verifier</artifactId>
    <scope>test</scope>
</dependency>

注意事项

  • 版本兼容性:需与 Spring Boot 2.2.x 配套使用,避免跨版本冲突。
  • 测试环境隔离:建议结合 @SpringBootTest@AutoConfigureMockMvc 进行全栈测试。
  • 合约更新策略:修改合约后需同步更新提供者实现和消费者期望,建议通过 CI/CD 流程自动化验证。

版本概述

Spring Cloud Contract 2.2.3 是 Spring Cloud 生态中的合约测试框架,基于 Spring Boot 2.2.x 版本构建,主要用于实现消费者驱动的合约测试(CDC)。该版本专注于稳定性改进和与 Spring Boot 的兼容性优化,适用于微服务场景下的契约验证。

核心功能

  • 契约定义:支持通过 Groovy 或 YAML 定义服务间交互的契约(如 HTTP 请求/响应、消息传递)。
  • 自动生成测试:根据契约自动生成生产者端测试代码(如 JUnit 或 Spock),验证接口实现是否符合契约。
  • 存根生成:为消费者端生成 WireMock 存根或消息契约,隔离依赖服务进行集成测试。
  • 与 Spring Cloud 集成:无缝兼容 Spring Cloud Netflix、OpenFeign 等组件。

关键改进

  • 依赖升级:适配 Spring Boot 2.2.8 及相关的 Spring Cloud 组件,修复潜在兼容性问题。
  • 性能优化:改进了契约解析和存根生成的效率,减少大型项目构建时间。
  • Bug 修复:修复了部分场景下 YAML 契约解析异常和消息契约的序列化问题。

使用示例(HTTP 契约)

Groovy 契约文件示例

Contract.make {
    request {
        method 'GET'
        url '/users/1'
    }
    response {
        status 200
        body([
            id: 1,
            name: $(regex('[a-zA-Z]+'))
        ])
        headers {
            contentType('application/json')
        }
    }
}

生成的测试代码
框架会自动生成基于 JUnit 的测试类,验证 /users/{id} 接口是否返回符合契约的响应。

升级建议

  • 若项目已使用 Spring Boot 2.2.x,推荐升级至 2.2.3 以获取稳定性修复。
  • 对于新项目,建议评估更高版本(如 3.x 系列),以获得更多新特性支持。

注意事项

  • 需确保生产者与消费者使用相同或兼容的契约版本,避免因字段变更导致测试失败。
  • 消息契约测试需配合 Spring Cloud Stream 等消息中间件使用。

相关工具

  • Spring Cloud Contract Verifier:核心模块,负责生成并执行测试。
  • Spring Cloud Contract Stub Runner:在消费者端启动嵌入式 WireMock 服务器加载存根。
  • Pact 兼容性:可通过插件与 Pact 契约格式互操作。
    Spring Cloud Contract 2.2.3
    Spring Cloud Contract is an umbrella project holding solutions that help users in successfully implementing the Consumer Driven Contracts approach. Currently Spring Cloud Contract consists of the Spring Cloud Contract Verifier project.

Spring Cloud Contract Verifier is a tool that enables Consumer Driven Contract (CDC) development of JVM-based applications. It is shipped with Contract Definition Language (DSL) written in Groovy or YAML. Contract definitions are used to produce following resources:

by default JSON stub definitions to be used by WireMock (HTTP Server Stub) when doing integration testing on the client code (client tests). Test code must still be written by hand, test data is produced by Spring Cloud Contract Verifier.

Messaging routes if you’re using one. We’re integrating with Spring Integration, Spring Cloud Stream and Apache Camel. You can however set your own integrations if you want to.

Acceptance tests (by default in JUnit or Spock) used to verify if server-side implementation of the API is compliant with the contract (server tests). Full test is generated by Spring Cloud Contract Verifier.

Spring Cloud Contract Verifier moves TDD to the level of software architecture.

To see how Spring Cloud Contract supports other languages just check out this blog post.
Features

When trying to test an application that communicates with other services then we could do one of two things:

deploy all microservices and perform end to end tests

mock other microservices in unit / integration tests

Both have their advantages but also a lot of disadvantages. Let’s focus on the latter. Deploy all microservices and perform end to end tests

Advantages:

simulates production

tests real communication between services

Disadvantages:

to test one microservice we would have to deploy 6 microservices, a couple of databases etc.

the environment where the tests would be conducted would be locked for a single suite of tests (i.e. nobody else would be able to run the tests in the meantime).

long to run

very late feedback

extremely hard to debug

Mock other microservices in unit / integration tests

Advantages:

very fast feedback

no infrastructure requirements

Disadvantages:

the implementor of the service creates stubs thus they might have nothing to do with the reality

you can go to production with passing tests and failing production

To solve the aforementioned issues Spring Cloud Contract Verifier with Stub Runner were created. Their main idea is to give you very fast feedback, without the need to set up the whole world of microservices.

Spring Cloud Contract Verifier features:

ensure that HTTP / Messaging stubs (used when developing the client) are doing exactly what actual server-side implementation will do

promote acceptance test driven development method and Microservices architectural style

to provide a way to publish changes in contracts that are immediately visible on both sides of the communication

to generate boilerplate test code used on the server side

Spring Boot Config
On the Producer Side

To start working with Spring Cloud Contract, you can add files with REST or messaging contracts expressed in either Groovy DSL or YAML to the contracts directory, which is set by the contractsDslDir property. By default, it is $rootDir/src/test/resources/contracts.

Then you can add the Spring Cloud Contract Verifier dependency and plugin to your build file, as the following example shows:

org.springframework.cloud spring-cloud-starter-contract-verifier test

The following listing shows how to add the plugin, which should go in the build/plugins portion of the file:

org.springframework.cloud spring-cloud-contract-maven-plugin ${spring-cloud-contract.version} true

Running ./mvnw clean install automatically generates tests that verify the application compliance with the added contracts. By default, the tests get generated under org.springframework.cloud.contract.verifier.tests.

As the implementation of the functionalities described by the contracts is not yet present, the tests fail.

To make them pass, you must add the correct implementation of either handling HTTP requests or messages. Also, you must add a base test class for auto-generated tests to the project. This class is extended by all the auto-generated tests, and it should contain all the setup information necessary to run them (for example RestAssuredMockMvc controller setup or messaging test setup).

The following example, from pom.xml, shows how to specify the base test class:

org.springframework.cloud spring-cloud-contract-maven-plugin ${spring-cloud-contract.version} true com.example.contractTest.BaseTestClass org.springframework.boot spring-boot-maven-plugin

INFO: The baseClassForTests element lets you specify your base test class. It must be a child of a configuration element within spring-cloud-contract-maven-plugin.

Once the implementation and the test base class are in place, the tests pass, and both the application and the stub artifacts are built and installed in the local Maven repository. You can now merge the changes, and you can publish both the application and the stub artifacts in an online repository. 2.2. On the Consumer Side

You can use Spring Cloud Contract Stub Runner in the integration tests to get a running WireMock instance or messaging route that simulates the actual service.

To do so, add the dependency to Spring Cloud Contract Stub Runner, as the following example shows:

org.springframework.cloud spring-cloud-starter-contract-stub-runner test

You can get the Producer-side stubs installed in your Maven repository in either of two ways:

By checking out the Producer side repository and adding contracts and generating the stubs by running the following commands:

$ cd local-http-server-repo
$ ./mvnw clean install -DskipTests

The tests are being skipped because the producer-side contract implementation is not in place yet, so the automatically-generated contract tests fail.

By getting already-existing producer service stubs from a remote repository. To do so, pass the stub artifact IDs and artifact repository URL as Spring Cloud Contract Stub Runner properties, as the following example shows:

stubrunner:
  ids: 'com.example:http-server-dsl:+:stubs:8080'
  repositoryRoot: https://repo.spring.io/libs-snapshot

Now you can annotate your test class with @AutoConfigureStubRunner. In the annotation, provide the group-id and artifact-id values for Spring Cloud Contract Stub Runner to run the collaborators’ stubs for you, as the following example shows:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment=WebEnvironment.NONE)
@AutoConfigureStubRunner(ids = {“com.example:http-server-dsl:+:stubs:6565”},
stubsMode = StubRunnerProperties.StubsMode.LOCAL)
public class LoanApplicationServiceTests {

Use the REMOTE stubsMode when downloading stubs from an online repository and LOCAL for offline work.

Now, in your integration test, you can receive stubbed versions of HTTP responses or messages that are expected to be emitted by the collaborator service.

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Bol5261

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值