Spring Cloud Contract 2.2.2 是 Spring Cloud Contract 的一个版本,于 2020 年 3 月发布。Spring Cloud Contract 是一个用于实现消费者驱动契约(Consumer-Driven Contracts, CDC)的工具,帮助开发者在微服务架构中定义、测试和验证服务之间的契约。以下是关于该版本的详细介绍:
1. 核心功能
Spring Cloud Contract 2.2.2 的主要功能包括:
- 契约定义:通过 Groovy 或 YAML 文件定义服务之间的契约。
- 自动生成测试:根据契约自动生成生产者端和消费者端的测试代码。
- 契约验证:确保生产者和消费者之间的交互符合定义的契约。
- 与 Spring Cloud 集成:与 Spring Cloud 生态系统无缝集成,支持 Spring Boot 应用。
2. 使用场景
Spring Cloud Contract 2.2.2 适用于以下场景:
- 微服务架构:在微服务架构中定义和验证服务之间的契约。
- 消费者驱动契约:通过消费者驱动契约确保服务之间的兼容性。
- 自动化测试:通过自动生成的测试代码提升测试覆盖率和质量。
3. 快速入门
3.1 添加依赖
在 Maven 项目中添加 Spring Cloud Contract 的依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-contract-verifier</artifactId>
<version>2.2.2.RELEASE</version>
<scope>test</scope>
</dependency>
3.2 定义契约
在 src/test/resources/contracts
目录下定义契约文件(Groovy 或 YAML):
org.springframework.cloud.contract.spec.Contract.make {
request {
method 'GET'
url '/example'
}
response {
status 200
body('Hello, World!')
}
}
3.3 生成测试
运行 Maven 命令生成生产者端的测试代码:
mvn clean install
3.4 验证契约
在消费者端使用生成的 Stub 文件验证契约:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
@AutoConfigureStubRunner(ids = {"com.example:producer:+:stubs:8080"}, stubsMode = StubRunnerProperties.StubsMode.LOCAL)
public class ConsumerContractTest {
@Test
public void testExample() {
RestTemplate restTemplate = new RestTemplate();
String response = restTemplate.getForObject("http://localhost:8080/example", String.class);
assertThat(response).isEqualTo("Hello, World!");
}
}
4. 注意事项
- 版本兼容性:Spring Cloud Contract 2.2.2 需要 Spring Boot 2.2.x 版本。
- 契约管理:确保契约文件与生产者和消费者的实际实现保持一致。
- 测试覆盖:通过自动生成的测试代码提升测试覆盖率,确保服务之间的兼容性。
5. 总结
Spring Cloud Contract 2.2.2 是一个强大的工具,帮助开发者在微服务架构中定义、测试和验证服务之间的契约。通过自动生成测试代码和与 Spring Cloud 生态系统的无缝集成,开发者可以更高效地构建和管理微服务应用。如果需要更详细的使用指南或示例代码,可以参考 Spring Cloud Contract 官方文档 和相关资源。
如果需要进一步了解其技术细节或实践案例,可以参考以下资源:
Spring Cloud Contract 2.2.2.RELEASE 介绍
Spring Cloud Contract 2.2.2.RELEASE 是 Spring Cloud Contract 的一个稳定版本,于 2020 年 3 月 5 日发布。
主要特性与更新
-
契约测试增强:
- 提供了更强大的契约测试功能,支持多种消息中间件(如 Kafka、RabbitMQ)。
- 支持与 Pact 的集成,方便开发者使用 Pact 的契约定义和测试工具。
-
依赖升级:
- 该版本对内部依赖进行了升级,以确保与 Spring Boot 2.2.x 和其他 Spring Cloud 组件(如 Spring Cloud Hoxton.SR3)的兼容性。
-
错误修复与改进:
- 修复了多个已知问题,包括一些与契约验证和消息传递相关的错误。
- 提供了更详细的文档和示例,帮助开发者快速上手。
-
Stub Runner 支持:
- 提供了
spring-cloud-contract-stub-runner
组件,用于在测试中运行和管理契约定义的桩服务。
- 提供了
使用方法
-
添加依赖:
如果您想在项目中使用 Spring Cloud Contract 2.2.2.RELEASE,可以通过以下 Maven 依赖引入:<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-contract-core</artifactId> <version>2.2.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-contract-pact</artifactId> <version>2.2.2.RELEASE</version> </dependency>
同时,您也可以根据需要引入其他相关模块,如
spring-cloud-contract-stub-runner
。 -
配置契约测试:
在项目中定义契约文件,并通过 Spring Cloud Contract 提供的注解或工具进行契约验证。例如:@SpringBootTest @AutoConfigureStubRunner public class ContractTest { @Test public void testContract() { // 测试逻辑 } }
官方文档与资源
- 官方文档:您可以通过 Spring Cloud Contract 官方文档 获取更多详细信息。
- Maven 仓库:相关依赖可以在 Maven Repository 中找到。
希望这些信息对您有帮助!如果您有其他问题或需要进一步的指导,请随时告知。
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 testThe 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} trueRunning ./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-pluginINFO: 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 testYou 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.
Spring Cloud Contract是一个伞形项目,它拥有帮助用户成功实现消费者驱动的合同方法的解决方案。目前Spring Cloud Contract由springcloudcontract验证程序项目组成。
SpringCloudContractVerifier是一个支持基于JVM的应用程序的消费者驱动契约(CDC)开发的工具。它附带了用Groovy或YAML编写的契约定义语言(Contract Definition Language,DSL)。合同定义用于生成以下资源:
默认情况下,WireMock(HTTP服务器存根)在对客户端代码进行集成测试(客户端测试)时使用的JSON存根定义。测试代码仍然必须手工编写,测试数据由Spring Cloud合同验证程序生成。
如果您使用的是消息传递路由。我们正在与Spring集成、Spring云流和Apache Camel集成。但是,如果需要,可以设置自己的集成。
验收测试(默认情况下在JUnit或Spock中)用于验证API的服务器端实现是否符合约定(服务器测试)。完整测试由Spring云契约验证程序生成。
SpringCloudContractVerifier将TDD移动到软件架构的级别。
要了解Spring Cloud Contract如何支持其他语言,请查看这篇博客文章。
特征
当尝试测试与其他服务通信的应用程序时,我们可以执行以下两项操作之一:
部署所有微服务并执行端到端测试
模拟单元/集成测试中的其他微服务
两者各有利弊。让我们关注后者。部署所有微服务并执行端到端测试