### Maven Install Log for HTTP Server Stubs
Source: https://github.com/spring-cloud/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/getting-started/cdc.adoc
This log snippet shows the output from the Maven install plugin, confirming that the `http-server` JAR, POM, and stubs JAR have been successfully installed into the local Maven repository. This step is crucial for making the stubs available for consumer-side testing.
```bash
[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.jar
[INFO] Installing /some/path/http-server/pom.xml to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.pom
[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar
```
--------------------------------
### Generate Producer Stubs Locally (Consumer)
Source: https://github.com/spring-cloud/spring-cloud-contract/blob/main/docs/src/main/asciidoc/sagan-boot.adoc
This Bash command sequence shows how to navigate to a producer-side repository and generate stubs locally by running a Maven clean install. The `-DskipTests` flag is used to bypass failing contract tests if the producer-side implementation is not yet complete.
```Bash
$ cd local-http-server-repo
$ ./mvnw clean install -DskipTests
```
--------------------------------
### Install Maven Project and Skip Tests
Source: https://github.com/spring-cloud/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/getting-started/cdc.adoc
These commands navigate into the cloned repository and then execute a Maven clean install, explicitly skipping test execution. This is useful when you only want to generate and install stubs without running the full test suite, especially from the consumer's perspective.
```bash
cd local-http-server-repo
./mvnw clean install -DskipTests
```
--------------------------------
### JAX-RS Client Contract Test Example
Source: https://github.com/spring-cloud/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/getting-started/first-application.adoc
An example of a generated Spring Cloud Contract test using a JAX-RS client. It shows how to build a GET request with multiple query parameters and assert the HTTP status and JSON response.
```java
@SuppressWarnings("rawtypes")
public class FooTest {
WebTarget webTarget;
@Test
public void validate_() throws Exception {
// when:
Response response = webTarget
.path("/users")
.queryParam("limit", "10")
.queryParam("offset", "20")
.queryParam("filter", "email")
.queryParam("sort", "name")
.queryParam("search", "55")
.queryParam("age", "99")
.queryParam("name", "Denis.Stepanov")
.queryParam("email", "bob@email.com")
.request()
.build("GET")
.invoke();
String responseAsString = response.readEntity(String.class);
// then:
assertThat(response.getStatus()).isEqualTo(200);
// and:
DocumentContext parsedJson = JsonPath.parse(responseAsString);
assertThatJson(parsedJson).field("['property1']").isEqualTo("a");
}
```
--------------------------------
### Example Non-Spring Javalin Application
Source: https://github.com/spring-cloud/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/using/provider-contract-testing-non-spring.adoc
This Java code provides a minimal example of a non-Spring HTTP server built with Javalin. It demonstrates how to start a simple web application that can be used as a provider for contract testing when Spring's `MockMvc` setup is not applicable.
```java
package com.example.demo;
import io.javalin.Javalin;
public class DemoApplication {
public static void main(String[] args) {
new DemoApplication().run(7000);
}
public Javalin start(int port) {
return Javalin.create().start(port);
}
public Javalin registerGet(Javalin app) {
return app.get("/", ctx -> ctx.result("Hello World"));
}
public Javalin run(int port) {
return registerGet(start(port));
}
}
```
--------------------------------
### Python Flask Application Basic Setup
Source: https://github.com/spring-cloud/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/docker-project.adoc
This snippet provides the foundational code for a Flask web application in Python. It imports necessary modules like `Flask`, `jsonify`, `pika` (for RabbitMQ interaction), and `os`, and initializes the Flask application instance. This serves as a starting point for building the HTTP message triggering endpoint.
```python
#!/usr/bin/env python
from flask import Flask
from flask import jsonify
import pika
import os
app = Flask(__name__)
```
--------------------------------
### Spring Cloud Stream Function Configuration Example
Source: https://github.com/spring-cloud/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/project-features-messaging.adoc
This Groovy snippet shows an example of a Spring Cloud Stream function configuration, likely used within a test context. The `include` directive suggests it's pulling a code block tagged 'setup' from a larger test file.
```groovy
include::{tests_path}/spring-cloud-contract-stub-runner-stream/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=setup,indent=0]
```
--------------------------------
### Install Producer Stubs Locally (Consumer)
Source: https://github.com/spring-cloud/spring-cloud-contract/blob/main/spring-cloud-contract-stub-runner/src/test/resources/git_samples/contract-predefined-names-git/README.adoc
Instructions for consumers to install producer stubs locally from the contract repository, enabling offline development and testing against the producer's API. This command navigates to the specific contract version directory and performs a Maven install.
```bash
cd src/main/resources/contracts/com/example/beer-api-producer-external/1.0.0
mvn clean install -DskipTests
```
--------------------------------
### View Maven Build and Stub Installation Logs for Spring Cloud Contract
Source: https://github.com/spring-cloud/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/getting-started/first-application.adoc
This bash snippet displays the console output of a Maven build process for a Spring Cloud Contract project. It shows the generation of stubs, packaging of application and stub JARs, and their installation into the local Maven repository.
```bash
[INFO] --- spring-cloud-contract-maven-plugin:1.0.0.BUILD-SNAPSHOT:generateStubs (default-generateStubs) @ http-server ---
[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar
[INFO]
[INFO] --- maven-jar-plugin:2.6:jar (default-jar) @ http-server ---
[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar
[INFO]
[INFO] --- spring-boot-maven-plugin:1.5.5.BUILD-SNAPSHOT:repackage (default) @ http-server ---
[INFO]
[INFO] --- maven-install-plugin:2.5.2:install (default-install) @ http-server ---
[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.jar
[INFO] Installing /some/path/http-server/pom.xml to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.pom
[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar
```
--------------------------------
### Install Contract Definitions Locally
Source: https://github.com/spring-cloud/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/using/cdc-external-repo.adoc
This command installs the contract definitions into the local Maven repository, making them available for local builds and subsequent consumption by other projects.
```bash
./mvnw clean install
```
--------------------------------
### Example Loan Application Service Test (Java)
Source: https://github.com/spring-cloud/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/getting-started/cdc.adoc
This entry refers to a Java test file for the Loan Application Service, demonstrating how a consumer would write a test for a new feature. The test checks if a loan application for a large amount is correctly rejected by the system, aligning with the Consumer Driven Contract approach.
```Java
File: samples/standalone/dsl/http-client/src/test/java/com/example/loan/LoanApplicationServiceTests.java
// This file contains a test to verify that a loan application for a big amount
// is rejected with an appropriate description, as per the new feature requirement.
// The actual code content is external and linked via the documentation.
```
--------------------------------
### Spring Cloud Contract Git Protocol URL Examples
Source: https://github.com/spring-cloud/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/howto/how-to-use-git-as-storage.adoc
This snippet provides examples of how to specify Git repository URLs using the 'git://' protocol prefix for Spring Cloud Contract. These examples demonstrate connecting to local file system paths, HTTPS-based GitHub repositories, and SSH-based GitHub repositories.
```text
git://file:///foo/bar
git://https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git
git://git@github.com:spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git
```
--------------------------------
### Spring Cloud Contract Verifier YAML Body Matcher Configuration Examples
Source: https://github.com/spring-cloud/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/project-features-contract/dsl-dynamic-properties.adoc
These YAML examples demonstrate how to configure body matchers. The first example shows a standard regex matcher with a specified regex type. The second example illustrates using a predefined regular expression for common patterns.
```YAML
- path: $.thing1
type: by_regex
value: thing2
regexType: as_string
```
```YAML
- path: $.thing1
type: by_regex
predefined: only_alpha_unicode
```
--------------------------------
### PlantUML Diagram for Fraud Detection Flow
Source: https://github.com/spring-cloud/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/getting-started/cdc.adoc
This PlantUML diagram illustrates the workflow for the producer side (Fraud Detection server) in a consumer-driven contract setup. It shows the steps involved, from taking over a pull request and setting up the Spring Cloud Contract plugin to running the build and generating tests and stub artifacts.
```plantuml
"Fraud\nDetection"->"Fraud\nDetection": take over the\n pull request
"Fraud\nDetection"->"Fraud\nDetection": setup\nSpring Cloud\nContract plugin
"Fraud\nDetection"->"Fraud\nDetection\nBuild": run the build
"Fraud\nDetection\nBuild"->"SCC Plugin": generate tests\nstubs \nand stubs artifact \n(e.g. stubs-jar)
"SCC Plugin"->"Fraud\nDetection\nBuild": tests and stubs generated
```
--------------------------------
### Clone Spring Cloud Contract Node.js Sample Repository
Source: https://github.com/spring-cloud/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/docker-project.adoc
These bash commands are used to clone a sample Node.js project from GitHub and then navigate into a specific subdirectory. This is a prerequisite for running the Stub Runner example with the provided Node.js application.
```bash
$ git clone https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs
$ cd bookstore
```
--------------------------------
### Install Producer Stubs Locally for Consumer Offline Development (Bash)
Source: https://github.com/spring-cloud/spring-cloud-contract/blob/main/spring-cloud-contract-stub-runner/src/test/resources/git_samples/contract-git/README.adoc
This bash command sequence allows a consumer to navigate into a specific contract directory and install producer stubs locally using Maven. This enables the consumer to work offline and test against the producer's API without requiring a live producer service.
```bash
cd src/main/resources/contracts/com/example/beer-api-producer-external/1.0.0
mvn clean install -DskipTests
```
--------------------------------
### Spring Cloud Build Checkstyle Directory Structure
Source: https://github.com/spring-cloud/spring-cloud-contract/blob/main/README.adoc
This snippet illustrates the directory structure of the `spring-cloud-build-tools` module, highlighting the location of the default Checkstyle rules, file header setup, and suppression rules. It provides a visual guide to where these configuration files reside.
```Text
spring-cloud-build-tools/
----
└── src
├── checkstyle
│ └── checkstyle-suppressions.xml <3>
└── main
└── resources
├── checkstyle-header.txt <2>
└── checkstyle.xml <1>
```
--------------------------------
### WebTestClient Contract Test Example (Reactive)
Source: https://github.com/spring-cloud/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/getting-started/first-application.adoc
An example of a generated Spring Cloud Contract test using WebTestClient, recommended for Reactive/Web-Flux applications. It demonstrates a POST request, asserting status code, content type, and parsing JSON response.
```java
@Test
public void validate_shouldRejectABeerIfTooYoung() throws Exception {
// given:
WebTestClientRequestSpecification request = given()
.header("Content-Type", "application/json")
.body("{\"age\":10}");
// when:
WebTestClientResponse response = given().spec(request)
.post("/check");
// then:
assertThat(response.statusCode()).isEqualTo(200);
assertThat(response.header("Content-Type")).matches("application/json.*");
// and:
DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
assertThatJson(parsedJson).field("['status']").isEqualTo("NOT_OK");
}
```
--------------------------------
### Install Producer Stubs Locally for Consumer Testing
Source: https://github.com/spring-cloud/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/using/cdc-external-repo.adoc
This snippet demonstrates how a consumer can navigate to the producer's contract directory within the cloned external repository and install the producer's stubs locally using Maven. This step is crucial for the consumer to fetch and run an in-memory HTTP server stub for testing against the producer's defined contracts.
```bash
cd src/main/resource/contracts/producer
./mvnw clean install
```
--------------------------------
### Spring Cloud Contract Stub Runner Startup Console Output
Source: https://github.com/spring-cloud/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/docker-project.adoc
This snippet displays the typical console output observed when the Spring Cloud Contract Stub Runner successfully initializes and starts. It indicates that the Camel context and StubRunnerBoot have started, and the Spring DispatcherServlet is ready to handle requests.
```bash
o.a.c.impl.engine.AbstractCamelContext : Apache Camel 3.4.3 (camel-1) started in 0.007 seconds
o.s.c.c.s.server.StubRunnerBoot : Started StubRunnerBoot in 14.483 seconds (JVM running for 18.666)
o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
o.s.web.servlet.DispatcherServlet : Completed initialization in 2 ms
```
--------------------------------
### Configure Spring Cloud Contract Maven Plugin with Base Test Class
Source: https://github.com/spring-cloud/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/getting-started/three-second-tour.adoc
This `pom.xml` snippet shows how to configure the `spring-cloud-contract-maven-plugin` to specify a `baseClassForTests`. This class is extended by auto-generated tests and provides necessary setup information, such as `RestAssuredMockMvc` controller setup or messaging test setup, to ensure tests run correctly.
```XML
org.springframework.cloud
spring-cloud-contract-maven-plugin
2.1.2.RELEASE
true
com.example.contractTest.BaseTestClass
org.springframework.boot
spring-boot-maven-plugin
```
--------------------------------
### Spring Application Configuration Example
Source: https://github.com/spring-cloud/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/project-features-messaging.adoc
This YAML snippet shows an example of Spring application configuration, likely for a test environment. The `include` directive suggests it's pulling content from an `application.yml` file, which might contain properties related to stub runner or messaging.
```yaml
include::{tests_path}/spring-cloud-contract-stub-runner-stream/src/test/resources/application.yml[]
```
--------------------------------
### Add Spring Cloud Contract Verifier Maven Plugin
Source: https://github.com/spring-cloud/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/getting-started/cdc.adoc
This XML snippet demonstrates how to add the Spring Cloud Contract Verifier Maven plugin to the `pom.xml`. This plugin is crucial for generating and running tests, as well as producing and installing stubs based on defined contracts.
```xml
4.0.0
org.springframework.cloud
spring-cloud-contract-maven-plugin
3.1.3
true
com.example.BaseClass
com.example
http-server
0.0.1-SNAPSHOT
stubs
```
--------------------------------
### Spring Cloud Contract Consumer-Side Final Process Flow
Source: https://github.com/spring-cloud/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/getting-started/cdc.adoc
This PlantUML diagram illustrates the comprehensive workflow for a Spring Cloud Contract consumer service (Loan Issuance) in its final stage. It details the steps from merging the feature branch to master, setting up and starting the SCC Stub Runner, fetching stubs from storage, running tests against the stub, and finally, the successful test execution.
```plantuml
"Loan\nIssuance"->"Loan\nIssuance": merge the\nfeature branch\nto master branch
"Loan\nIssuance"->"Loan\nIssuance": setup SCC Stub Runner\nto fetch stubs\nfrom Stub Storage
"Loan\nIssuance"->"LI\nSCC\nStub Runner": start stubs\nof FD from\nStub Storage
"LI\nSCC\nStub Runner"->"Stub Storage": find stubs of [FD]
"Stub Storage"->"LI\nSCC\nStub Runner": stubs of [FD] found
"LI\nSCC\nStub Runner"->"FD stub": run stubs of [FD]
"FD stub"->"LI\nSCC\nStub Runner": [FD] stub is running
"LI\nSCC\nStub Runner"->"Loan\nIssuance": stubs running and ready for the test
"Loan\nIssuance"->"Loan\nIssuance": run a test
"Loan\nIssuance"->"FD stub": the test\nsends a request\nto the running stub
"FD stub"->"Loan\nIssuance": stub responds successfuly
"Loan\nIssuance"->"Loan\nIssuance": the test passes successfully
```
--------------------------------
### MockMvc Contract Test Example
Source: https://github.com/spring-cloud/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/getting-started/first-application.adoc
An example of a generated Spring Cloud Contract test using MockMvc for HTTP contract verification. It demonstrates making a PUT request, asserting status code, content type, and parsing JSON response with JsonPath.
```java
@Test
public void validate_shouldMarkClientAsFraud() throws Exception {
// given:
MockMvcRequestSpecification request = given()
.header("Content-Type", "application/vnd.fraud.v1+json")
.body("{\"client.id\":\"1234567890\",\"loanAmount\":99999}");
// when:
ResponseOptions response = given().spec(request)
.put("/fraudcheck");
// then:
assertThat(response.statusCode()).isEqualTo(200);
assertThat(response.header("Content-Type")).matches("application/vnd.fraud.v1.json.*");
// and:
DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
assertThatJson(parsedJson).field("['fraudCheckStatus']").matches("[A-Z]{5}");
assertThatJson(parsedJson).field("['rejection.reason']").isEqualTo("Amount too high");
}
```
--------------------------------
### Git Commands for Setting Up Contract Testing Branch
Source: https://github.com/spring-cloud/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/getting-started/cdc.adoc
These bash commands are used to create a new local branch (`contract-change-pr`) based on `master` and then pull changes from a remote fork. This prepares the development environment for implementing and testing contract changes.
```bash
$ git checkout -b contract-change-pr master
$ git pull https://your-git-server.com/server-side-fork.git contract-change-pr
```
--------------------------------
### Add Spring Cloud Contract Verifier Dependency (Producer)
Source: https://github.com/spring-cloud/spring-cloud-contract/blob/main/docs/src/main/asciidoc/sagan-boot.adoc
This XML snippet demonstrates how to include the `spring-cloud-starter-contract-verifier` dependency in a Maven `pom.xml`. This dependency is crucial for the producer side to enable the generation of tests that verify compliance with defined contracts.
```XML
org.springframework.cloud
spring-cloud-starter-contract-verifier
test
```
--------------------------------
### Run Spring Cloud Contract Stub Runner Docker Container Example
Source: https://github.com/spring-cloud/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/docker-project.adoc
This example demonstrates how to run the Spring Cloud Contract Stub Runner Docker image, configuring it with essential environment variables. It sets the Docker version, the IP address of the application, the port for Stub Runner, the coordinates of the stubs to run, and the repository root for fetching stubs.
```bash
# Provide the Spring Cloud Contract Docker version
$ SC_CONTRACT_DOCKER_VERSION="..."
# The IP at which the app is running and Docker container can reach it
$ APP_IP="192.168.0.100"
# Spring Cloud Contract Stub Runner properties
$ STUBRUNNER_PORT="8083"
# Stub coordinates 'groupId:artifactId:version:classifier:port'
$ STUBRUNNER_IDS="com.example:bookstore:0.0.1.RELEASE:stubs:9876"
$ STUBRUNNER_REPOSITORY_ROOT="http://${APP_IP}:8081/artifactory/libs-release-local"
```
--------------------------------
### Start Docker Infrastructure for Development
Source: https://github.com/spring-cloud/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/docker-project.adoc
Executes a shell script to initialize the necessary Docker infrastructure, which typically includes services like Node.js and Artifactory, essential for the application and contract testing environment.
```Shell
./setup_infra.sh
```
--------------------------------
### Configure Spring Cloud Contract Maven Plugin (Producer)
Source: https://github.com/spring-cloud/spring-cloud-contract/blob/main/docs/src/main/asciidoc/sagan-boot.adoc
This XML snippet shows how to add the `spring-cloud-contract-maven-plugin` to the `build/plugins` section of a Maven `pom.xml`. This plugin is responsible for processing contracts, generating tests, and building stub artifacts on the producer side.
```XML
org.springframework.cloud
spring-cloud-contract-maven-plugin
${spring-cloud-contract.version}
true
```
--------------------------------
### Generate Tests and Stubs Locally (Producer)
Source: https://github.com/spring-cloud/spring-cloud-contract/blob/main/spring-cloud-contract-stub-runner/src/test/resources/git_samples/contract-predefined-names-git/README.adoc
Instructions for producers to generate tests and stubs from the root of the contracts repository, allowing offline work after consumers have filed a contract pull request. This command executes the Maven wrapper to clean and install the project.
```bash
./mvnw clean install -DskipTests
```
--------------------------------
### Configure Stub Runner for Runtime Stub Generation in Java
Source: https://github.com/spring-cloud/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/project-features-stubrunner/stub-runner-generate-stubs-at-runtime.adoc
These Java code examples demonstrate how to configure Spring Cloud Contract Stub Runner to generate stubs at runtime. This feature allows consumers to fetch stubs immediately, bypassing the need for producers to publish them first. It involves setting `generateStubs` to `true` and specifying the repository root and artifact IDs. The examples cover configuration via `@AutoConfigureStubRunner` annotation, JUnit 4 `StubRunnerRule`, and JUnit 5 `StubRunnerExtension`.
```java
@AutoConfigureStubRunner(
stubsMode = StubRunnerProperties.StubsMode.REMOTE,
repositoryRoot = "stubs://file://location/to/the/contracts",
ids = "com.example:some-producer",
generateStubs = true)
```
```java
@Rule
public StubRunnerRule rule = new StubRunnerRule()
.downloadStub("com.example:some-producer")
.repoRoot("stubs://file://location/to/the/contracts")
.stubsMode(StubRunnerProperties.StubsMode.REMOTE)
.withGenerateStubs(true);
```
```java
@RegisterExtension
public StubRunnerExtension stubRunnerExtension = new StubRunnerExtension()
.downloadStub("com.example:some-producer")
.repoRoot("stubs://file://location/to/the/contracts")
.stubsMode(StubRunnerProperties.StubsMode.REMOTE)
.withGenerateStubs(true);
```
--------------------------------
### Configuring Spring Cloud Contract Stub Runner for Git Stubs
Source: https://github.com/spring-cloud/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/using/provider-contract-testing-with-stubs-in-git.adoc
These Java examples demonstrate how to configure the Spring Cloud Contract Stub Runner to fetch stubs directly from a Git repository. The 'repositoryRoot' property is set to a Git URL using the 'git://' protocol, allowing the consumer to retrieve stubs without relying on a binary repository. Examples are provided for annotation-based configuration, JUnit 4 Rule, and JUnit 5 Extension.
```java
@AutoConfigureStubRunner(
stubsMode = StubRunnerProperties.StubsMode.REMOTE,
repositoryRoot = "git://git@github.com:spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git",
ids = "com.example:artifact-id:0.0.1")
```
```java
@Rule
public StubRunnerRule rule = new StubRunnerRule()
.downloadStub("com.example","artifact-id", "0.0.1")
.repoRoot("git://git@github.com:spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git")
.stubsMode(StubRunnerProperties.StubsMode.REMOTE);
```
```java
@RegisterExtension
public StubRunnerExtension stubRunnerExtension = new StubRunnerExtension()
.downloadStub("com.example","artifact-id", "0.0.1")
.repoRoot("git://git@github.com:spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git")
.stubsMode(StubRunnerProperties.StubsMode.REMOTE);
```
--------------------------------
### Configure Spring Cloud Contract Maven Plugin with Base Test Class (Producer)
Source: https://github.com/spring-cloud/spring-cloud-contract/blob/main/docs/src/main/asciidoc/sagan-boot.adoc
This XML snippet illustrates how to configure the `spring-cloud-contract-maven-plugin` to specify a `baseClassForTests`. This base class is extended by all auto-generated contract tests and should contain common setup logic, such as `RestAssuredMockMvc` or messaging test configurations, required for the tests to pass.
```XML
org.springframework.cloud
spring-cloud-contract-maven-plugin
${spring-cloud-contract.version}
true
com.example.contractTest.BaseTestClass
org.springframework.boot
spring-boot-maven-plugin
```
--------------------------------
### Clone Producer Service Repository
Source: https://github.com/spring-cloud/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/getting-started/cdc.adoc
This command clones the server-side repository of the Fraud Detection service from a specified Git URL into a local directory. This is the first step to interact with the producer's contract.
```bash
git clone https://your-git-server.com/server-side.git local-http-server-repo
```
--------------------------------
### Defining an HTTP Stub with WireMock JSON
Source: https://github.com/spring-cloud/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/project-features-stubrunner/stub-runner-core.adoc
This JSON snippet defines a basic HTTP stub using WireMock syntax. It specifies a GET request to the '/ping' URL and a corresponding 200 OK response with 'pong' as the body and 'Content-Type: text/plain' header.
```json
{
"request": {
"method": "GET",
"url": "/ping"
},
"response": {
"status": 200,
"body": "pong",
"headers": {
"Content-Type": "text/plain"
}
}
}
```
--------------------------------
### Execute Stub Runner Boot Application
Source: https://github.com/spring-cloud/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/project-features-stubrunner/stub-runner-boot.adoc
This command line snippet demonstrates how to start a Stub Runner Boot application packaged as a JAR. The "${SYSTEM_PROPS}" placeholder allows for passing additional system properties to the Java Virtual Machine, which can be used for configuration or environment-specific settings, such as connecting to a service discovery instance like Eureka.
```Shell
java -jar ${SYSTEM_PROPS} stub-runner-boot-eureka-example.jar
```
--------------------------------
### Set up WebTestClient Base Class with RestAssured for WebFlux Testing
Source: https://github.com/spring-cloud/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/project-features-flows/feature-webflux.adoc
This example demonstrates how to create an abstract base class for WebFlux tests using `RestAssuredWebTestClient`. The `@Before` method initializes a standalone `ProducerController`, enabling isolated and efficient testing of WebFlux endpoints.
```java
import io.restassured.module.webtestclient.RestAssuredWebTestClient;
import org.junit.Before;
public abstract class BeerRestBase {
@Before
public void setup() {
RestAssuredWebTestClient.standaloneSetup(
new ProducerController(personToCheck -> personToCheck.age >= 20));
}
}
```
--------------------------------
### Set Up Repository for Common Spring Cloud Contracts
Source: https://github.com/spring-cloud/spring-cloud-contract/blob/main/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/site/asciidoc/configs.adoc
This snippet shows how to configure a repository that holds common contracts. It includes an option to exclude target or build folders, which is useful when installing stubs locally as a consumer to prevent unnecessary files from being included.
```XML
include::../../../src/test/projects/common-repo/pom.xml[tags=common_repo]
```
--------------------------------
### Build Spring Cloud Contract Producer Stubs
Source: https://github.com/spring-cloud/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/getting-started/three-second-tour.adoc
This command sequence navigates into the local HTTP server repository and builds the project using Maven, skipping tests. This is typically done to generate producer-side stubs for consumer-driven contract testing.
```bash
$ cd local-http-server-repo
$ ./mvnw clean install -DskipTests
```
--------------------------------
### Example WireMock Mappings JSON
Source: https://github.com/spring-cloud/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/project-features-stubrunner/stub-runner-core.adoc
This JSON array represents a typical WireMock mapping file, showing a single stub definition. It includes a unique ID, the request details (GET method to '/name'), and the response details (200 OK status with 'fraudDetectionServer' body).
```json
[
{
"id" : "f9152eb9-bf77-4c38-8289-90be7d10d0d7",
"request" : {
"url" : "/name",
"method" : "GET"
},
"response" : {
"status" : 200,
"body" : "fraudDetectionServer"
},
"uuid" : "f9152eb9-bf77-4c38-8289-90be7d10d0d7"
},
...
]
```
--------------------------------
### Download and Run Stub Runner Boot Fat JAR
Source: https://github.com/spring-cloud/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/project-features-stubrunner/stub-runner-boot.adoc
This Bash script illustrates how to download a specific version of the Stub Runner Boot standalone JAR from Maven Central using `wget`. Following the download, it shows how to execute the JAR using `java -jar`, passing essential configuration properties like `stubrunner.ids` and `stubrunner.repositoryRoot` for specifying which stubs to load and their source.
```bash
$ wget -O stub-runner.jar 'https://search.maven.org/remotecontent?filepath=org/springframework/cloud/spring-cloud-contract-stub-runner-boot/2.0.1.RELEASE/spring-cloud-contract-stub-runner-boot-2.0.1.RELEASE.jar'
$ java -jar stub-runner.jar --stubrunner.ids=... --stubrunner.repositoryRoot=...
```
--------------------------------
### Example Java HTTP Client for Fraud Check
Source: https://github.com/spring-cloud/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/getting-started/cdc.adoc
A conceptual Java code snippet demonstrating how a client application might send a PUT request to the '/fraudcheck' endpoint. It includes a client ID and loan amount in the request body, targeting a service running on port 8080.
```java
package com.example.loan;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.Map;
public class LoanApplicationService {
private final RestTemplate restTemplate = new RestTemplate();
private final String FRAUD_SERVICE_URL = "http://localhost:8080/fraudcheck";
public void sendFraudCheckRequest(String clientId, int loanAmount) {
Map requestBody = new HashMap<>();
requestBody.put("client", Map.of("id", clientId));
requestBody.put("loanAmount", loanAmount);
// Assuming a PUT request for fraud check
restTemplate.put(FRAUD_SERVICE_URL, requestBody);
System.out.println("Sent fraud check request for client " + clientId + " with amount " + loanAmount);
}
public static void main(String[] args) {
LoanApplicationService service = new LoanApplicationService();
service.sendFraudCheckRequest("1234567890", 99999);
}
}
```
--------------------------------
### Cloning Spring Cloud Contract Node.js Sample Repository
Source: https://github.com/spring-cloud/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/docker-project.adoc
These commands clone the `spring-cloud-contract-nodejs` sample repository from GitHub and navigate into its root directory. This repository contains a simple MVC application used for demonstrating contract testing with Spring Cloud Contract, providing a practical example for integration.
```bash
$ git clone https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs
$ cd bookstore
```
--------------------------------
### Java Base Class for Spring Cloud Contract MockMvc Tests with Spring Context
Source: https://github.com/spring-cloud/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/maven-project.adoc
This Java example illustrates how to set up a base abstract class for Spring Cloud Contract Verifier tests, integrating with a full Spring application context. It uses `@SpringBootTest` and `@Autowired` to configure `RestAssuredMockMvc` with the `WebApplicationContext`, allowing for comprehensive context setup.
```Java
import io.restassured.module.mockmvc.RestAssuredMockMvc;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.context.WebApplicationContext;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = SomeConfig.class, properties="some=property")
public abstract class BaseTestClass {
@Autowired
WebApplicationContext context;
@Before
public void setup() {
RestAssuredMockMvc.webAppContextSetup(this.context);
}
}
```
--------------------------------
### Generate Spring Cloud Contract Documentation
Source: https://github.com/spring-cloud/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/building.adoc
Runs a script to generate documentation for both the root Spring Cloud Contract project and its Maven plugin.
```shell
./scripts/generateDocs.sh
```
--------------------------------
### Java Contract Test Method for Fraud Detection Service
Source: https://github.com/spring-cloud/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/getting-started/cdc.adoc
This JUnit test method is an example of an auto-generated contract test for a fraud detection service. It uses Rest Assured to simulate an HTTP PUT request to `/fraudcheck` with specific headers and body, then asserts on the response status code, headers, and JSON content, demonstrating the 'red' phase of TDD.
```java
@Test
public void validate_shouldMarkClientAsFraud() throws Exception {
// given:
MockMvcRequestSpecification request = given()
.header("Content-Type", "application/vnd.fraud.v1+json")
.body("{\"client.id\":\"1234567890\",\"loanAmount\":99999}");
// when:
ResponseOptions response = given().spec(request)
.put("/fraudcheck");
// then:
assertThat(response.statusCode()).isEqualTo(200);
assertThat(response.header("Content-Type")).matches("application/vnd.fraud.v1.json.*");
// and:
DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
assertThatJson(parsedJson).field("['fraudCheckStatus']").matches("[A-Z]{5}");
assertThatJson(parsedJson).field("['rejection.reason']").isEqualTo("Amount too high");
}
```
--------------------------------
### Add Spring Cloud Contract Gradle Plugin and Dependencies
Source: https://github.com/spring-cloud/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/gradle-project.adoc
This section provides multiple ways to add the Spring Cloud Contract Verifier Gradle plugin and its dependencies to your project. It covers configurations for GA versions using the modern `plugins` DSL, non-GA versions requiring `pluginManagement` setup, and a legacy `buildscript` approach. All examples include common test dependencies like Groovy and Spock.
```Groovy
// build.gradle
plugins {
id "groovy"
// this will work only for GA versions of Spring Cloud Contract
id "org.springframework.cloud.contract" version "${GAVerifierVersion}"
}
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-contract-dependencies:${GAVerifierVersion}"
}
}
dependencies {
testImplementation "org.apache.groovy:groovy-all:${groovyVersion}"
// example with adding Spock core and Spock Spring
testImplementation "org.spockframework:spock-core:${spockVersion}"
testImplementation "org.spockframework:spock-spring:${spockVersion}"
testImplementation 'org.springframework.cloud:spring-cloud-starter-contract-verifier'
}
```
```Groovy
// settings.gradle
pluginManagement {
plugins {
id "org.springframework.cloud.contract" version "${verifierVersion}"
}
repositories {
// to pick from local .m2
mavenLocal()
// for snapshots
maven { url "https://repo.spring.io/snapshot" }
// for milestones
maven { url "https://repo.spring.io/milestone" }
// for GA versions
gradlePluginPortal()
}
}
// build.gradle
plugins {
id "groovy"
id "org.springframework.cloud.contract"
}
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-contract-dependencies:${verifierVersion}"
}
}
dependencies {
testImplementation "org.apache.groovy:groovy-all:${groovyVersion}"
// example with adding Spock core and Spock Spring
testImplementation "org.spockframework:spock-core:${spockVersion}"
testImplementation "org.spockframework:spock-spring:${spockVersion}"
testImplementation 'org.springframework.cloud:spring-cloud-starter-contract-verifier'
}
```
```Groovy
// build.gradle
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath "org.springframework.boot:spring-boot-gradle-plugin:${springboot_version}"
classpath "org.springframework.cloud:spring-cloud-contract-gradle-plugin:${verifier_version}"
// here you can also pass additional dependencies such as Kotlin spec e.g.:
// classpath "org.springframework.cloud:spring-cloud-contract-spec-kotlin:${verifier_version}"
}
}
apply plugin: 'groovy'
apply plugin: 'org.springframework.cloud.contract'
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-contract-dependencies:${verifier_version}"
}
}
dependencies {
testImplementation "org.apache.groovy:groovy-all:${groovyVersion}"
// example with adding Spock core and Spock Spring
testImplementation "org.spockframework:spock-core:${spockVersion}"
testImplementation "org.spockframework:spock-spring:${spockVersion}"
testImplementation 'org.springframework.cloud:spring-cloud-starter-contract-verifier'
}
```
--------------------------------
### Spring Cloud Contract Workflow UML Diagram
Source: https://github.com/spring-cloud/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/getting-started/first-application.adoc
Illustrates the high-level workflow and interactions between the API Producer, Build process, Stub Storage (e.g., Nexus/Artifactory), API Consumer, and Spring Cloud Contract Stub Runner. It shows how contracts and stubs are generated, uploaded, and consumed.
```PlantUML
"API Producer"->"API Producer": add Spring Cloud \nContract (SCC) plugin
"API Producer"->"API Producer": add SCC Verifier dependency
"API Producer"->"API Producer": define contracts
"API Producer"->"Build": run build
"Build"->"SCC Plugin": generate \ntests, stubs and stubs \nartifact (e.g. stubs-jar)
"Build"->"Stub Storage": upload contracts \nand stubs and the project arifact
"Build"->"API Producer": Build successful
"API Consumer"->"API Consumer": add SCC Stub Runner \ndependency
"API Consumer"->"API Consumer": write a SCC Stub Runner \nbased contract test
"SCC Stub Runner"->"Stub Storage": test asks for [API Producer] stubs
"Stub Storage"->"SCC Stub Runner": fetch the [API Producer] stubs
"SCC Stub Runner"->"SCC Stub Runner": run in memory\n HTTP server stubs
"API Consumer"->"SCC Stub Runner": send a request \nto the HTTP server stub
"SCC Stub Runner"->"API Consumer": communication is correct
```
--------------------------------
### Add Spring Cloud Contract Stub Runner Dependency (Consumer)
Source: https://github.com/spring-cloud/spring-cloud-contract/blob/main/docs/src/main/asciidoc/sagan-boot.adoc
This XML snippet demonstrates how to include the `spring-cloud-starter-contract-stub-runner` dependency in a Maven `pom.xml`. This dependency is used on the consumer side to run WireMock instances or messaging routes that simulate the actual service based on producer-generated stubs.
```XML
org.springframework.cloud
spring-cloud-starter-contract-stub-runner
test
```
--------------------------------
### Configure Spring Cloud Contract Stub Runner for Remote Git Repository
Source: https://github.com/spring-cloud/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/howto/how-to-use-git-as-storage.adoc
This Java code snippet demonstrates how to configure Spring Cloud Contract's `@AutoConfigureStubRunner` annotation to fetch contract stubs from a remote Git repository. It sets the `stubsMode` to `REMOTE`, specifies the `repositoryRoot` using the `git://` protocol for a GitHub repository, and defines the `ids` of the contracts to be used. This setup automates the cloning of the Git project, discovery of stub definitions, and starting of stub servers for integration testing.
```java
@AutoConfigureStubRunner(
stubsMode="REMOTE",
repositoryRoot="git://https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git",
ids="com.example:bookstore:0.0.1.RELEASE"
)
```
--------------------------------
### Example Custom WireMock Extension Implementation (Groovy)
Source: https://github.com/spring-cloud/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/customization/wiremock-customization.adoc
This example shows a basic structure for a custom WireMock extension implemented in Groovy. Such an extension would implement the `org.springframework.cloud.contract.verifier.dsl.wiremock.WireMockExtensions` interface to provide custom WireMock behaviors.
```Groovy
package org.springframework.cloud.contract.verifier.dsl.wiremock
import com.github.tomakehurst.wiremock.extension.Extension
import com.github.tomakehurst.wiremock.extension.ResponseTransformer
class TestWireMockExtensions implements WireMockExtensions {
@Override
Collection extends Extension> getExtensions() {
return [new ResponseTransformer() {
@Override
String getName() {
return "my-custom-transformer"
}
@Override
boolean applyGlobally() {
return true
}
@Override
com.github.tomakehurst.wiremock.client.ResponseDefinitionTransformer apply(
com.github.tomakehurst.wiremock.client.ResponseDefinition responseDefinition,
com.github.tomakehurst.wiremock.http.Request request,
com.github.tomakehurst.wiremock.core.Admin admin) {
// Your custom transformation logic here
return responseDefinition
}
}]
}
}
```
--------------------------------
### Build Spring Cloud Contract Producer Project
Source: https://github.com/spring-cloud/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/getting-started/first-application.adoc
This Bash snippet demonstrates how to build a Spring Cloud Contract producer project using Maven. The `-DskipTests` flag is used to bypass tests, which is often necessary when the producer-side contract implementation is not yet complete, preventing test failures.
```bash
cd local-http-server-repo
./mvnw clean install -DskipTests
```
--------------------------------
### Example Directory Structure for Contracts and Stubs with find-producer Enabled
Source: https://github.com/spring-cloud/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/project-features-stubrunner/stub-runner-stubs-protocol.adoc
This 'bash' snippet illustrates the recommended directory structure for storing contracts and stub mappings when the 'stubs.find-producer=true' property is used. It shows how contracts and mappings for different consumers are organized under their respective artifact IDs within a group ID directory.
```Bash
└── com.example <1>
├── some-artifact-id <2>
│ └── 0.0.1
│ ├── contracts <3>
│ │ └── shouldReturnStuffForArtifactId.groovy
│ └── mappings <4>
│ └── shouldReturnStuffForArtifactId.json
└── some-other-artifact-id <5>
├── contracts
│ └── shouldReturnStuffForOtherArtifactId.groovy
└── mappings
└── shouldReturnStuffForOtherArtifactId.json
```
--------------------------------
### Configure StubRunner for Development or Production Stubs in Java
Source: https://github.com/spring-cloud/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/howto/how-to-do-stubs-versioning.adoc
These Java `@AutoConfigureStubRunner` configurations illustrate how to manipulate the classifier to select different versions of stubs. The first example uses the default 'stubs' classifier for development versions, while the second example uses 'prod-stubs' to target stubs deployed for production environments.
```java
@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:8080"})
```
```java
@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:prod-stubs:8080"})
```
--------------------------------
### Run Spring Cloud Contract Stub Runner Docker with RabbitMQ Middleware
Source: https://github.com/spring-cloud/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/docker-project.adoc
This example demonstrates how to run the Spring Cloud Contract Stub Runner as a Docker container. It configures the stub runner to connect to RabbitMQ, fetch stubs from a remote Git repository, and expose its HTTP API port. It also shows how to mount a local Maven repository for faster startup.
```bash
docker run \
-e "CAMEL_COMPONENT_RABBITMQ_ADDRESSES=172.18.0.1:5672" \
-e "STUBRUNNER_IDS=group:application:0.0.1-SNAPSHOT" \
-e "STUBRUNNER_REPOSITORY_ROOT=git://https://github.com/marcingrzejszczak/cdct_python_contracts.git" \
-e ADDITIONAL_OPTS="--thin.properties.dependencies.rabbitmq=org.apache.camel.springboot:camel-rabbitmq-starter:3.4.0" \
-e "STUBRUNNER_STUBS_MODE=REMOTE" \
-v "${HOME}/.m2/:/home/scc/.m2:rw" \
-p 8750:8750 \
springcloud/spring-cloud-contract-stub-runner:3.0.4-SNAPSHOT
```
--------------------------------
### Example of Explicitly Namespaced XML Document and XPath
Source: https://github.com/spring-cloud/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/project-features-contract/_dsl-xml.adoc
This snippet provides an example of an XML document that uses an explicitly defined namespace. It also shows the correct XPath expression required to select an element within such a namespaced document, highlighting the need to include the namespace prefix in the XPath.
```XML
customer@test.com
The XPath expression to select the email address is: `/ns1:customer/email/text()`.
```