I've previously posted about defining Consumer Driven Contracts using the OpenAPI specification and Spring Cloud Contract. This approach works well because you can tie your contracts to your API specification, and also wire in a request validator into your contract tests.

But one problem that remained is typically your OpenAPI specification will span multiple services. Thus, when generating contract tests, you'd get tests generated for all services and not just a specific service.

This leads to headaches in your CI/CD process. If you ran the tests at the service level, contract tests for other services would, of course, fail.

Ideally you'd want contract testing at the service level, and not downstream at the scope of the OpenAPI specification.

At this point, if you do nothing, all contracts in the spec will still be parsed.

To filter on the service name, the parser will read a system environment variable called scc.enabled.servicenames.

Spring Cloud Contacts are typically generated via the SCC Maven or Gradle plugins. The plugin configuration is upstream of the parser, thus a system environment variable was the best configuration solution.

For use with Maven, setting the system environment variable is simple. You can use a Maven plugin as shown below.

Here, I'm setting the environment variable to the artifact id. Thus my 'serviceName' is the same as the Maven artifactId. A good idea from my buddy Mike R.

The value can be any string value. Or any comma separated list of string values if you wish to activate multiple serviceNames.

One side note - if a contact does not have a serviceName value set, the parser will still pick it up.

One other note, if your configuration does not produce any contracts, the SCC Maven plugin will throw an exception. Currently, the SCC YamlContract parser is picking up the OpenAPI YAML document and throwing an exception when trying to parse it. This should be fixed in the next release of Spring Cloud Contract. See this issue for details. At the time of writing, Spring Cloud Contract is on version 2.1.1.RELEASE. I expect the fix will make the next release of Spring Cloud Contract.

Through this configuration, you can have one OpenAPI specification for your APIs, and then re-use the specification to generate contracts at the individual service level.

This post was specifically about using the new service name feature. If you'd like to learn more about defining consumer driven contracts in OpenAPI for Spring Cloud Contract, please see the home page of my project repository.