|
| 1 | +package de.rieckpil.blog.pact; |
| 2 | + |
| 3 | +import java.math.BigDecimal; |
| 4 | + |
| 5 | +import au.com.dius.pact.consumer.MockServer; |
| 6 | +import au.com.dius.pact.consumer.dsl.PactDslJsonBody; |
| 7 | +import au.com.dius.pact.consumer.dsl.PactDslWithProvider; |
| 8 | +import au.com.dius.pact.consumer.junit5.PactConsumerTestExt; |
| 9 | +import au.com.dius.pact.consumer.junit5.PactTestFor; |
| 10 | +import au.com.dius.pact.core.model.V4Pact; |
| 11 | +import au.com.dius.pact.core.model.annotations.Pact; |
| 12 | +import de.rieckpil.blog.portfolio.StockApiClient; |
| 13 | +import de.rieckpil.blog.portfolio.StockPrice; |
| 14 | +import org.junit.jupiter.api.Test; |
| 15 | +import org.junit.jupiter.api.extension.ExtendWith; |
| 16 | +import org.springframework.web.reactive.function.client.WebClient; |
| 17 | + |
| 18 | +import static org.assertj.core.api.Assertions.assertThat; |
| 19 | + |
| 20 | +@ExtendWith(PactConsumerTestExt.class) |
| 21 | +@PactTestFor(providerName = "stock-api") |
| 22 | +class StockApiContractTest { |
| 23 | + |
| 24 | + @Pact(consumer = "portfolio-dashboard") |
| 25 | + public V4Pact createPact(PactDslWithProvider builder) { |
| 26 | + // Define what we expect from the Stock API |
| 27 | + return builder |
| 28 | + .given("Stock AAPL exists and market is open") |
| 29 | + .uponReceiving("A request for AAPL stock price") |
| 30 | + .path("/api/stocks/AAPL/price") |
| 31 | + .method("GET") |
| 32 | + .willRespondWith() |
| 33 | + .status(200) |
| 34 | + .body(new PactDslJsonBody() |
| 35 | + .stringType("symbol", "AAPL") |
| 36 | + .decimalType("price", 150.25) |
| 37 | + .stringType("currency", "USD") |
| 38 | + .datetime("timestamp", "yyyy-MM-dd'T'HH:mm:ss'Z'")) |
| 39 | + .toPact(V4Pact.class); |
| 40 | + } |
| 41 | + |
| 42 | + @Test |
| 43 | + @PactTestFor(pactMethod = "createPact") |
| 44 | + void testGetStockPrice(MockServer mockServer) { |
| 45 | + // Create client pointing to mock server |
| 46 | + StockApiClient client = new StockApiClient(WebClient.builder().baseUrl(mockServer.getUrl()).build()); |
| 47 | + |
| 48 | + // Test the interaction |
| 49 | + StockPrice price = client.getStockPrice("AAPL"); |
| 50 | + |
| 51 | + assertThat(price) |
| 52 | + .isNotNull() |
| 53 | + .satisfies(p -> { |
| 54 | + assertThat(p.getSymbol()).isEqualTo("AAPL"); |
| 55 | + assertThat(p.getPrice()).isGreaterThan(BigDecimal.ZERO); |
| 56 | + assertThat(p.getCurrency()).isEqualTo("USD"); |
| 57 | + }); |
| 58 | + } |
| 59 | +} |
0 commit comments