pact-foundation / pact-jvm

JVM version of Pact. Enables consumer driven contract testing, providing a mock service and DSL for the consumer project, and interaction playback and verification for the service provider project.
https://docs.pact.io
Apache License 2.0
1.08k stars 479 forks source link

Junit5 + SpringBootHttpTarget #824

Closed tomasAlabes closed 5 years ago

tomasAlabes commented 5 years ago

Hi, first thank you for the work done with this library!

I've been using the junit5 provider example, but when I want to use the random port with spring boot, I have to use the junit4 runner @RunWith(SpringRestPactRunner.class), which starts executing the tests with junit4. So I have to revert the junit5 parts.

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ExtendWith(SpringExtension::class)
@RunWith(SpringRestPactRunner::class)
@Provider("Blah")
@PactFolder("pacts")
class Contracts {

    @TestTarget
    @JvmField
    final val target: Target = SpringBootHttpTarget()

    /* to make it full junit4
    @TestTemplate
    @ExtendWith(PactVerificationInvocationContextProvider::class)
    fun pactVerificationTestTemplate(context: PactVerificationContext) {
        context.verifyInteraction()
    }
    */

I end up removing the TestTemplate and it works, but it would be nice to have a full junit5 story for this. Migrating-from-junit4-tips: @RunWith no longer exists; superseded by @ExtendWith. But only 1 @ExtendWith can be in the test.

Or maybe I'm missing a way of using it all with junit5?

Thanks!

uglyog commented 5 years ago

The SpringBootHttpTarget is a JUnit 4 target. You should be able to just use the JUnit 5 HttpTestTarget and then set the port in the template or a "before" method. You don't need a field like in the JUnit 4 tests.

JUnit 5 @ExtendWith annotation can take multiple extension classes. Have a look at this test where I'm using the Wiremock extension with the Pact one. I set the target in the "before" method because Wiremock is using a random port.

tomasAlabes commented 5 years ago

Hi @uglyog, thank you for your response! SpringRestPactRunner can't be used with ExtendWith because it doesn't extend the right spring class. But as you said, I set the target in the "before" method and it worked. I didn't see that snippet in the doc. Thanks!