Skip to content

Instantly share code, notes, and snippets.

@dnno
Last active December 20, 2022 13:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dnno/2fbb2f1118915739644f887ed28a2c73 to your computer and use it in GitHub Desktop.
Save dnno/2fbb2f1118915739644f887ed28a2c73 to your computer and use it in GitHub Desktop.
PactConsumerTest
public class PactConsumerTest {
@Test
public void getAllUsersPact() {
String expectedUsers = """
[
{
"id": 1,
"name": "Jane Doe"
},
{
"id": 2,
"name": "John Doe"
}
]
""";
RequestResponsePact pact = ConsumerPactBuilder
.consumer("UserConsumer")
.hasPactWith("UserService")
.uponReceiving("A request for a user list")
.path("/users")
.method("GET")
.willRespondWith()
.status(200)
.headers(Map.of("Content-Type", "application/json"))
.body(expectedUsers)
.toPact();
MockProviderConfig config = MockProviderConfig.createDefault();
PactVerificationResult result = runConsumerTest(pact, config, PactConsumerTest::getAllUsers);
if (result instanceof PactVerificationResult.Error) {
throw new RuntimeException(((PactVerificationResult.Error) result).getError());
}
assertEquals(new PactVerificationResult.Ok(
Arrays.asList(
new User(1, "Jane Doe"),
new User(2, "John Doe")
)), result);
}
private static List<User> getAllUsers(MockServer mockServer, PactTestExecutionContext context) {
RestTemplate restTemplate = new RestTemplateBuilder().rootUri(mockServer.getUrl()).build();
User[] resultingUsers = restTemplate.getForObject("/users", User[].class);
if (resultingUsers != null) {
return Arrays.stream(resultingUsers).toList();
} else {
return Collections.emptyList();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment