Pact Spring/JUnit runner
Overview
Library provides ability to play contract tests against a provider using Spring & JUnit. This library is based on and references the JUnit package, so see the Pact JUnit 4 or Pact JUnit 5 providers for more details regarding configuration using JUnit.
Supports:
Standard ways to load pacts from folders and broker
Easy way to change assertion strategy
Spring Test MockMVC Controllers and ControllerAdvice using MockMvc standalone setup.
MockMvc debugger output
Spring WebFlux Controllers and RouterFunctions
Multiple @State runs to test a particular Provider State multiple times
au.com.dius.pact.provider.junit.State custom annotation - before each interaction that requires a state change, all methods annotated by
@Statewith appropriate the state listed will be invoked.
NOTE: For publishing provider verification results to a pact broker, make sure the Java system property pact.provider.version
is set with the version of your provider.
Example of MockMvc test
Example of Spring WebFlux test
Using Spring runners
You can use SpringRestPactRunner or SpringMessagePactRunner instead of the default Pact runner to use the Spring test annotations. This will
allow you to inject or mock spring beans. SpringRestPactRunner is for restful webapps and SpringMessagePactRunner is
for async message tests.
For example:
Using Spring Context Properties
The SpringRestPactRunner will look up any annotation expressions (like ${pactBrokerHost})
above) from the Spring context. For Springboot, this will allow you to define the properties in the application test properties.
For instance, if you create the following application.yml in the test resources:
Then you can use the defaults on the @PactBroker annotation.
Using a random port with a Springboot test
If you use a random port in a springboot test (by setting SpringBootTest.WebEnvironment.RANDOM_PORT), you need to set it to the TestTarget. How this works is different for JUnit4 and JUnit5.
JUnit4
You can use the
SpringBootHttpTarget which will get the application port from the spring application context.
For example:
JUnit5
You actually don't need to dependend on pact-jvm-provider-spring for this. It's sufficient to depend on pact-jvm-provider-junit5.
You can set the port to the HttpTestTarget object in the before method.