Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

Spring Cloud Contract Tutorial

Overview

Spring Cloud Contract is a framework that supports Consumer-Driven Contracts (CDC) and contract tests. It helps in ensuring that services adhere to the agreed contract, allowing for more reliable and resilient microservices communication.

Key Features of Spring Cloud Contract

Spring Cloud Contract offers several features that facilitate contract-based development:

  • Consumer-Driven Contracts (CDC): Define and verify contracts between microservices.
  • Contract Testing: Automatically generate tests from contracts to ensure compliance.
  • Stub Generation: Generate stubs for testing consumers without requiring the actual provider service.
  • Integration with CI/CD: Easily integrate with CI/CD pipelines for automated contract verification.

Setting Up Spring Cloud Contract

To set up Spring Cloud Contract, add the following dependencies to your project:

// build.gradle
dependencies {
    implementation 'org.springframework.cloud:spring-cloud-starter-contract-verifier'
    testImplementation 'org.springframework.cloud:spring-cloud-starter-contract-stub-runner'
}

This adds the necessary dependencies for Spring Cloud Contract and stub runner for testing.

Defining a Contract

Create a contract file to define the interaction between the consumer and provider. Save it in the src/test/resources/contracts directory:

// src/test/resources/contracts/shouldReturnPerson.groovy
Contract.make {
    description "should return a person"
    request {
        method GET()
        url("/person/1")
    }
    response {
        status 200
        body([
            id: 1,
            name: "John Doe"
        ])
        headers {
            contentType(applicationJson())
        }
    }
}

This contract specifies that a GET request to /person/1 should return a 200 status with a JSON body.

Generating Tests

Spring Cloud Contract will automatically generate tests from the contracts. To generate the tests, run:

$ ./gradlew generateContractTests

The generated tests will be located in the build/generated-test-sources/contracts directory.

Implementing the Provider

Implement the provider service to satisfy the contract:

// PersonController.java
@RestController
public class PersonController {
    @GetMapping("/person/{id}")
    public ResponseEntity<Person> getPerson(@PathVariable Long id) {
        Person person = new Person(id, "John Doe");
        return ResponseEntity.ok(person);
    }
}

// Person.java
public class Person {
    private Long id;
    private String name;

    // Constructors, getters, and setters
}

The PersonController class defines the endpoint to return the person data as specified in the contract.

Running Contract Tests

Run the generated contract tests to verify that the provider meets the contract requirements:

$ ./gradlew test

The tests will validate that the provider service responds as expected based on the defined contract.

Using Stub Runner for Consumer Tests

Stub Runner allows you to use stubs generated from the contracts to test consumers without requiring the actual provider service:

// ConsumerTest.java
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureStubRunner(ids = "com.example:provider:+:stubs:8080")
public class ConsumerTest {
    @Autowired
    private RestTemplate restTemplate;

    @Test
    public void shouldReturnPerson() {
        ResponseEntity<Person> response = restTemplate.getForEntity("http://localhost:8080/person/1", Person.class);
        assertEquals(200, response.getStatusCodeValue());
        assertEquals("John Doe", response.getBody().getName());
    }
}

The @AutoConfigureStubRunner annotation configures Stub Runner to run the stubs on port 8080, allowing the consumer test to interact with the stub instead of the actual provider.

Key Points

  • Spring Cloud Contract supports Consumer-Driven Contracts (CDC) and contract tests.
  • Define and verify contracts between microservices to ensure compliance.
  • Automatically generate tests from contracts to validate provider implementations.
  • Generate stubs for testing consumers without requiring the actual provider service.
  • Integrate with CI/CD pipelines for automated contract verification.

Conclusion

Spring Cloud Contract is a powerful framework for ensuring reliable communication between microservices through Consumer-Driven Contracts and contract testing. By leveraging its features, developers can create robust and resilient microservices that adhere to defined contracts, leading to more stable and predictable systems. Happy coding!