contract-testing-demo
pact and java contract testing with micro-commits
AnimalServicePactTest.java
(2621B)
1 import au.com.dius.pact.consumer.ConsumerPactBuilder;
2 import au.com.dius.pact.consumer.dsl.PactDslWithProvider;
3 import au.com.dius.pact.model.RequestResponsePact;
4 import org.junit.Test;
5
6 import java.util.HashMap;
7 import java.util.Map;
8
9 import static org.junit.Assert.*;
10
11 public class AnimalServicePactTest {
12
13 private PactDslWithProvider withProvider =
14 ConsumerPactBuilder
15 .consumer("Zoo Service")
16 .hasPactWith("Animal Service");
17
18 @Test
19 public void alligatorMaryExists() {
20 Map<String, String> headers = new HashMap<>();
21 headers.put("Content-type", "application/json");
22
23 RequestResponsePact pact = withProvider
24 .given("there exists an alligator named Mary")
25 .uponReceiving("a request for Mary the alligator")
26 .method("GET")
27 .path("/alligators/Mary")
28 .willRespondWith()
29 .status(200)
30 .headers(headers)
31 .body("{\"name\": \"Mary\"}")
32 .toPact();
33
34 AnimalServiceHelper.consume(pact, animalService -> {
35 Alligator alligator = animalService.getAlligator("Mary");
36 assertEquals("Mary", alligator.getName());
37 });
38 }
39
40 @Test
41 public void alligatorMaryDoesNotExist() {
42 RequestResponsePact pact = withProvider
43 .given("there does not exist an alligator named Mary")
44 .uponReceiving("a request for Mary the alligator")
45 .method("GET")
46 .path("/alligators/Mary")
47 .willRespondWith()
48 .status(404)
49 .toPact();
50
51 AnimalServiceHelper.consume(pact, animalService -> {
52 Alligator alligator = animalService.getAlligator("Mary");
53 assertNull(alligator);
54 });
55 }
56
57 @Test
58 public void animalServiceIsUnavailable() {
59 RequestResponsePact pact = withProvider
60 .given("the service is unavailable")
61 .uponReceiving("a request for Mary the alligator")
62 .method("GET")
63 .path("/alligators/Mary")
64 .willRespondWith()
65 .status(500)
66 .toPact();
67
68 AnimalServiceHelper.consume(pact, animalService -> {
69 try {
70 animalService.getAlligator("Mary");
71 fail("getAlligator() did not throw exception");
72 } catch (Exception e) {
73 assertEquals(AnimalServiceUnavailableException.class, e.getClass());
74 }
75 });
76 }
77 }