Migrating Pact Contract Tests from JUnit4 to JUnit5

This blog explains how to migrate the contract tests from JUnit4 to JUnit5.

28.04.2020

Tags

This is a companion piece to the blog post Writing Contract Tests with Pact in Spring Boot. It explains how to migrate the contract tests from JUnit4 to JUnit5.

Consumer

Step 1: Upgrade Dependencies

Instead of pact-jvm-consumer-java8_2.12 you need pact-jvm-consumer-java8and pact-jvm-consumer-junit5.

Step 2: Update Test Code

As before, the contract is created by a unit test.

On the class-level, the @PactProviderRuleMk2 rule was replaced by the PactConsumerTestExt extension and a new class-level annotation @PactTestFor.

Example:

Replace

public class UserServiceContractTest {  @Rule public PactProviderRuleMk2 provider = new PactProviderRuleMk2("user-service", null, 8080, this);  ...} 

with

@ExtendWith(PactConsumerTestExt.class)@PactTestFor(providerName = "user-service", port = "8080")public class UserServiceContractTest {  ...}

On the method-level, the @PactVerification annotation was replaced with the @PactTestFor annotation.

Example:

Replace

@PactVerification(fragment = "pactUserExists")@Testpublic void userExists() { ...}

with

@PactTestFor(pactMethod = "pactUserExists")@Testpublic void userExists() { ...}

Provider

Step 1: Upgrade Dependencies

Instead of pact-jvm-provider-spring_2.12 you need pact-jvm-provider-junit5. A dedicated spring library pact-jvm-provider-junit5-spring also exist. At the moment (March 2020) it only adds the option to resolve properties like the pact broker URL from the application.yml file.

Step 2: Update Test Code

The SpringRestPactRunner was replaced by the PactVerificationInvocationContextProvider extension that is used in combination with a test template.

Example:

Remove the

@RunWith(SpringRestPactRunner.class)

annotation from the class and add the following method:

@TestTemplate@ExtendWith(PactVerificationInvocationContextProvider.class)void pactVerificationTestTemplate(PactVerificationContext context) {   context.verifyInteraction();}

The SpringBootHttpTarget target does not (yet?) exist. Thus, you need to use the regular HttpTestTarget and set it as target in a beforeEach method.

Example:

Replace

@TestTargetpublic final Target target = new SpringBootHttpTarget();

with

@LocalServerPortprivate int port;@BeforeEachvoid before(PactVerificationContext context) {   context.setTarget(new HttpTestTarget("localhost", port));}

That’s it! 😃 You’ve upgraded your Pact tests from JUnit4 to JUnit5.

The updated code from the original blog post can be found here.


Source: Pact Logo
Source: JUnit5 Logo