</>

Technology

Rest Assured

Difficulty

Advanced

Interview Question

What is contract testing and when should you use it?

Answer

Contract Testing

Contract testing is a technique for testing an integration point by checking each application in isolation to ensure the messages it sends or receives conform to a shared understanding documented in a contract.

When to Use Contract Testing

Contract testing is immediately applicable anywhere where you have two services that need to communicate — such as an API client and a web front-end.

It really shines in an environment with many services (as is common in a microservice architecture). Having well-formed contract tests makes it easy for developers to avoid version hell.

Consumer-Driven Contract Testing

In microservices, the consumer (client) defines what it expects from the provider (API server). The contract is tested independently on both sides.

CODE
Consumer (Frontend) ──→ defines expected API shape ──→ Contract
Provider (API Server) ──→ verifies it fulfils the contract ──→ Pass/Fail

Popular Tools

ToolLanguageDescription
PactJava, JS, Ruby, .NETMost popular consumer-driven contract testing
Spring Cloud ContractJava/SpringContract testing for Spring microservices
DreddAnyAPI Blueprint/OpenAPI contract testing

Example with Pact (Java)

Java
@ExtendWith(PactConsumerTestExt.class)
public class UserServiceConsumerTest {

    @Pact(consumer = "FrontendApp", provider = "UserAPI")
    public RequestResponsePact createPact(PactDslWithProvider builder) {
        return builder
            .given("user 1 exists")
            .uponReceiving("get user by id")
                .path("/api/users/1")
                .method("GET")
            .willRespondWith()
                .status(200)
                .body(new PactDslJsonBody()
                    .integerType("id", 1)
                    .stringType("name", "John"))
            .toPact();
    }
}

Contract Testing vs Integration Testing

FeatureContract TestingIntegration Testing
IsolationTests each service independentlyTests services together
SpeedFastSlower
FeedbackEarly detectionLate detection
EnvironmentNo live environment neededNeeds running services

Contract testing is a killer app for microservice development and deployment.

Follow AutomateQA

Related Topics