Page cover image

OpenAPI Contract testing

API contract testing involves verifying whether an API behaves as expected according to its agreed-upon contract. The contract, defined by the method's signature, specifies what the method needs from callers and what it returns.

API contract testing helps to detect compatibility issues early in the development process. By validating the API contract, teams can ensure that changes to one service do not unintentionally break functionality for other services relying on it.

To execute Contract testing, we need a test that creates application context and configures the MockMvc. In the resource folder we need to store the existing OpenAPI JSON. Once test is started, it will verify the consistency of the OpenAPI (api-docs) by comparing the current OpenAPI JSON obtained from the running application with the version generated when the API was last changed. The test will fail if the API was modified. If the API change was intentional and approved as part of an update, developers would need to modify the stored OpenAPI JSON to reflect the new API specifications.

In most scenarios, we also need additional information and formatted output, hence we can extend the test to automatically store the temporary file, representing the new version of the OpenAPI. This file can then be used to update the original OpenAPI documentation.

If the method cannot fulfil the contract, the test assertion will fail, and we can conclude that the API contract has been broken.

Last updated