liveBook · Manning

Pact mock server

As explained in Contract Testing in Action

A Pact mock server is a test server that intercepts consumer requests and returns responses registered in Pact interactions.

A Pact mock server lets a consumer test its real API client against an agreed response without calling the live provider. Redirect the client URL to the mock server, register an interaction, and the test intercepts the request and returns the specified response. This keeps the contract close to consumer code when request details change. section 5.2

A consumer interaction defines both sides of an expected exchange:

  • Provider and consumer identities, such as MoviesAPI and MoviesAndroidApp. section 5.2
  • A provider state and request: GET /movies when a movie exists. section 5.2
  • A response: HTTP 200, an application/json header, and a JSON array whose movie fields have expected types. section 5.2
  • A test that constructs the production client with the mock-server URL, calls it, and asserts on the result. section 5.2

Testing a movie client

Create a synchronous Pact interaction for GET /movies, then inject mockServer.getUrl() into MovieClient. Calling getMovies() exercises the same client and repository path used by the app while the mock server supplies the registered movie response. The resulting interactions are converted into a Pact file. section 5.2

A mock-server contract test does not replace integration testing. Use an integration test against the real URL to verify configuration and authorization, while the Pact test checks the consumer’s expected request and response contract. section 5.2

Figure 5.6 Pact interaction contains the mobile app’s actual request intercepted and the expected response returned from the mock server. Finally, the interactions are converted to a Pact file.
figure

Follow the request from the mobile client through interception, the registered response, and conversion of interactions into a Pact file. section 5.2

How Contract Testing in Action covers it

How deep it goes
Walks through JUnit setup, interaction construction, mock-server injection, and a client assertion; defers real-service configuration and authorization to integration tests.
Examples
Uses a Kotlin MoviesAndroidApp client requesting GET /movies and receiving a typed JSON movie array with HTTP 200.
What it assumes
Introduces Android internals as nonessential while assuming a Kotlin client, repository, and JUnit 5 test environment.
What you can do after
Apply it via Pact and JUnit 5 to redirect a client to a mock server and verify a registered interaction.
How it connects
Connects consumer-driven contract testing with API clients, repositories, HTTP requests, JSON response matching, and integration testing.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Contract Testing in Action. The section links point to the parts of the book it draws on.