All Downloads are FREE. Search and download functionalities are using the official Maven repository.

Download JAR files tagged by pactfolder with all dependencies

Search JAR files by class name

pact-jvm-provider-junit5-spring from group au.com.dius (version 4.0.10)

# Pact Spring/JUnit5 Support This module extends the base [Pact JUnit5 module](../pact-jvm-provider-junit5). See that for more details. For writing Spring Pact verification tests with JUnit 5, there is an JUnit 5 Invocation Context Provider that you can use with the `@TestTemplate` annotation. This will generate a test for each interaction found for the pact files for the provider. To use it, add the `@Provider` and `@ExtendWith(SpringExtension.class)` and one of the pact source annotations to your test class (as per a JUnit 5 test), then add a method annotated with `@TestTemplate` and `@ExtendWith(PactVerificationSpringProvider.class)` that takes a `PactVerificationContext` parameter. You will need to call `verifyInteraction()` on the context parameter in your test template method. For example: ```java @ExtendWith(SpringExtension.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) @Provider("Animal Profile Service") @PactBroker public class ContractVerificationTest { @TestTemplate @ExtendWith(PactVerificationSpringProvider.class) void pactVerificationTestTemplate(PactVerificationContext context) { context.verifyInteraction(); } } ``` You will now be able to setup all the required properties using the Spring context, e.g. creating an application YAML file in the test resources: ```yaml pactbroker: host: your.broker.host auth: username: broker-user password: broker.password ``` You can also run pact tests against `MockMvc` without need to spin up the whole application context which takes time and often requires more additional setup (e.g. database). In order to run lightweight tests just use `@WebMvcTest` from Spring and `MockMvcTestTarget` as a test target before each test. For example: ```java @WebMvcTest @Provider("myAwesomeService") @PactBroker class ContractVerificationTest { @Autowired private MockMvc mockMvc; @TestTemplate @ExtendWith(PactVerificationInvocationContextProvider.class) void pactVerificationTestTemplate(PactVerificationContext context) { context.verifyInteraction(); } @BeforeEach void before(PactVerificationContext context) { context.setTarget(new MockMvcTestTarget(mockMvc)); } } ``` You can also use `MockMvcTestTarget` for tests without spring context by providing the controllers manually. For example: ```java @Provider("myAwesomeService") @PactFolder("pacts") class MockMvcTestTargetStandaloneMockMvcTestJava { @TestTemplate @ExtendWith(PactVerificationInvocationContextProvider.class) void pactVerificationTestTemplate(PactVerificationContext context) { context.verifyInteraction(); } @BeforeEach void before(PactVerificationContext context) { MockMvcTestTarget testTarget = new MockMvcTestTarget(); testTarget.setControllers(new DataResource()); context.setTarget(testTarget); } @RestController static class DataResource { @GetMapping("/data") @ResponseStatus(HttpStatus.NO_CONTENT) void getData(@RequestParam("ticketId") String ticketId) { } } } ``` **Important:** Since `@WebMvcTest` starts only Spring MVC components you can't use `PactVerificationSpringProvider` and need to fallback to `PactVerificationInvocationContextProvider`

Group: au.com.dius Artifact: pact-jvm-provider-junit5-spring
Show all versions Show documentation Show source 
 

0 downloads
Artifact pact-jvm-provider-junit5-spring
Group au.com.dius
Version 4.0.10
Last update 18. April 2020
Organization not specified
URL https://github.com/DiUS/pact-jvm
License Apache 2
Dependencies amount 0
Dependencies No dependencies
There are maybe transitive dependencies!

pact-jvm-provider-junit5_2.11 from group au.com.dius (version 3.5.24)

# Pact Junit 5 Extension ## Overview For writing Pact verification tests with JUnit 5, there is an JUnit 5 Invocation Context Provider that you can use with the `@TestTemplate` annotation. This will generate a test for each interaction found for the pact files for the provider. To use it, add the `@Provider` and one of the pact source annotations to your test class (as per a JUnit 4 test), then add a method annotated with `@TestTemplate` and `@ExtendWith(PactVerificationInvocationContextProvider.class)` that takes a `PactVerificationContext` parameter. You will need to call `verifyInteraction()` on the context parameter in your test template method. For example: ```java @Provider("myAwesomeService") @PactFolder("pacts") public class ContractVerificationTest { @TestTemplate @ExtendWith(PactVerificationInvocationContextProvider.class) void pactVerificationTestTemplate(PactVerificationContext context) { context.verifyInteraction(); } } ``` For details on the provider and pact source annotations, refer to the [Pact junit runner](../pact-jvm-provider-junit/README.md) docs. ## Test target You can set the test target (the object that defines the target of the test, which should point to your provider) on the `PactVerificationContext`, but you need to do this in a before test method (annotated with `@BeforeEach`). There are three different test targets you can use: `HttpTestTarget`, `HttpsTestTarget` and `AmpqTestTarget`. For example: ```java @BeforeEach void before(PactVerificationContext context) { context.setTarget(HttpTestTarget.fromUrl(new URL(myProviderUrl))); // or something like // context.setTarget(new HttpTestTarget("localhost", myProviderPort, "/")); } ``` ## Provider State Methods Provider State Methods work in the same way as with JUnit 4 tests, refer to the [Pact junit runner](../pact-jvm-provider-junit/README.md) docs. ## Modifying the requests before they are sent **Important Note:** You should only use this feature for things that can not be persisted in the pact file. By modifying the request, you are potentially modifying the contract from the consumer tests! Sometimes you may need to add things to the requests that can't be persisted in a pact file. Examples of these would be authentication tokens, which have a small life span. The Http and Https test targets support injecting the request that will executed into the test template method. You can then add things to the request before calling the `verifyInteraction()` method. For example to add a header: ```java @TestTemplate @ExtendWith(PactVerificationInvocationContextProvider.class) void testTemplate(PactVerificationContext context, HttpRequest request) { // This will add a header to the request request.addHeader("X-Auth-Token", "1234"); context.verifyInteraction(); } ``` ## Objects that can be injected into the test methods You can inject the following objects into your test methods (just like the `PactVerificationContext`). They will be null if injected before the supported phase. | Object | Can be injected from phase | Description | | ------ | --------------- | ----------- | | PactVerificationContext | @BeforeEach | The context to use to execute the interaction test | | Pact | any | The Pact model for the test | | Interaction | any | The Interaction model for the test | | HttpRequest | @TestTemplate | The request that is going to be executed (only for HTTP and HTTPS targets) | | ProviderVerifier | @TestTemplate | The verifier instance that is used to verify the interaction |

Group: au.com.dius Artifact: pact-jvm-provider-junit5_2.11
Show all versions Show documentation Show source 
 

2 downloads
Artifact pact-jvm-provider-junit5_2.11
Group au.com.dius
Version 3.5.24
Last update 04. November 2018
Organization not specified
URL https://github.com/DiUS/pact-jvm
License Apache 2
Dependencies amount 9
Dependencies kotlin-stdlib-jdk8, kotlin-reflect, slf4j-api, groovy-all, kotlin-logging, scala-library, scala-logging_2.11, pact-jvm-provider-junit_2.11, junit-jupiter-api,
There are maybe transitive dependencies!

pact-jvm-provider-spring_2.12 from group au.com.dius (version 3.6.15)

# Pact Spring/JUnit runner ## Overview Library provides ability to play contract tests against a provider using Spring & JUnit. This library is based on and references the JUnit package, so see the [Pact JUnit 4](../pact-jvm-provider-junit) or [Pact JUnit 5](../pact-jvm-provider-junit5) providers for more details regarding configuration using JUnit. Supports: - Standard ways to load pacts from folders and broker - Easy way to change assertion strategy - Spring Test MockMVC Controllers and ControllerAdvice using MockMvc standalone setup. - MockMvc debugger output - Multiple @State runs to test a particular Provider State multiple times - **au.com.dius.pact.provider.junit.State** custom annotation - before each interaction that requires a state change, all methods annotated by `@State` with appropriate the state listed will be invoked. **NOTE:** For publishing provider verification results to a pact broker, make sure the Java system property `pact.provider.version` is set with the version of your provider. ## Example of MockMvc test ```java @RunWith(RestPactRunner.class) // Custom pact runner, child of PactRunner which runs only REST tests @Provider("myAwesomeService") // Set up name of tested provider @PactFolder("pacts") // Point where to find pacts (See also section Pacts source in documentation) public class ContractTest { //Create an instance of your controller. We cannot autowire this as we're not using (and don't want to use) a Spring test runner. @InjectMocks private AwesomeController awesomeController = new AwesomeController(); //Mock your service logic class. We'll use this to create scenarios for respective provider states. @Mock private AwesomeBusinessLogic awesomeBusinessLogic; //Create an instance of your controller advice (if you have one). This will be passed to the MockMvcTarget constructor to be wired up with MockMvc. @InjectMocks private AwesomeControllerAdvice awesomeControllerAdvice = new AwesomeControllerAdvice(); //Create a new instance of the MockMvcTarget and annotate it as the TestTarget for PactRunner @TestTarget public final MockMvcTarget target = new MockMvcTarget(); @Before //Method will be run before each test of interaction public void before() { //initialize your mocks using your mocking framework MockitoAnnotations.initMocks(this); //configure the MockMvcTarget with your controller and controller advice target.setControllers(awesomeController); target.setControllerAdvice(awesomeControllerAdvice); } @State("default", "no-data") // Method will be run before testing interactions that require "default" or "no-data" state public void toDefaultState() { target.setRunTimes(3); //let's loop through this state a few times for a 3 data variants when(awesomeBusinessLogic.getById(any(UUID.class))) .thenReturn(myTestHelper.generateRandomReturnData(UUID.randomUUID(), ExampleEnum.ONE)) .thenReturn(myTestHelper.generateRandomReturnData(UUID.randomUUID(), ExampleEnum.TWO)) .thenReturn(myTestHelper.generateRandomReturnData(UUID.randomUUID(), ExampleEnum.THREE)); } @State("error-case") public void SingleUploadExistsState_Success() { target.setRunTimes(1); //tell the runner to only loop one time for this state //you might want to throw exceptions to be picked off by your controller advice when(awesomeBusinessLogic.getById(any(UUID.class))) .then(i -> { throw new NotCoolException(i.getArgumentAt(0, UUID.class).toString()); }); } } ``` ## Using a Spring runner (version 3.5.7+) You can use `SpringRestPactRunner` instead of the default Pact runner to use the Spring test annotations. This will allow you to inject or mock spring beans. For example: ```java @RunWith(SpringRestPactRunner.class) @Provider("pricing") @PactBroker(protocol = "https", host = "${pactBrokerHost}", port = "443", authentication = @PactBrokerAuth(username = "${pactBrokerUser}", password = "${pactBrokerPassword}")) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) public class PricingServiceProviderPactTest { @MockBean private ProductClient productClient; // This will replace the bean with a mock in the application context @TestTarget @SuppressWarnings(value = "VisibilityModifier") public final Target target = new HttpTarget(8091); @State("Product X010000021 exists") public void setupProductX010000021() throws IOException { reset(productClient); ProductBuilder product = new ProductBuilder() .withProductCode("X010000021"); when(productClient.fetch((Set<String>) argThat(contains("X010000021")), any())).thenReturn(product); } @State("the product code X00001 can be priced") public void theProductCodeX00001CanBePriced() throws IOException { reset(productClient); ProductBuilder product = new ProductBuilder() .withProductCode("X00001"); when(productClient.find((Set<String>) argThat(contains("X00001")), any())).thenReturn(product); } } ``` ### Using Spring Context Properties (version 3.5.14+) From version 3.5.14 onwards, the SpringRestPactRunner will look up any annotation expressions (like `${pactBrokerHost}`) above) from the Spring context. For Springboot, this will allow you to define the properties in the application test properties. For instance, if you create the following `application.yml` in the test resources: ```yaml pactbroker: host: "your.broker.local" port: "443" protocol: "https" auth: username: "<your broker username>" password: "<your broker password>" ``` Then you can use the defaults on the `@PactBroker` annotation. ```java @RunWith(SpringRestPactRunner.class) @Provider("My Service") @PactBroker( authentication = @PactBrokerAuth(username = "${pactbroker.auth.username}", password = "${pactbroker.auth.password}") ) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class PactVerificationTest { ``` ### Using a random port with a Springboot test (version 3.5.14+) If you use a random port in a springboot test (by setting `SpringBootTest.WebEnvironment.RANDOM_PORT`), you can use the `SpringBootHttpTarget` which will get the application port from the spring application context. For example: ```java @RunWith(SpringRestPactRunner.class) @Provider("My Service") @PactBroker @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class PactVerificationTest { @TestTarget public final Target target = new SpringBootHttpTarget(); } ```

Group: au.com.dius Artifact: pact-jvm-provider-spring_2.12
Show all versions Show documentation Show source 
 

1 downloads
Artifact pact-jvm-provider-spring_2.12
Group au.com.dius
Version 3.6.15
Last update 29. April 2020
Organization not specified
URL https://github.com/DiUS/pact-jvm
License Apache 2
Dependencies amount 5
Dependencies pact-jvm-provider-junit_2.12, spring-boot-starter-test, spring-webmvc, javax.servlet-api, jackson-datatype-joda,
There are maybe transitive dependencies!

pact-jvm-provider-junit5_2.12 from group au.com.dius (version 3.6.15)

# Pact Junit 5 Extension ## Overview For writing Pact verification tests with JUnit 5, there is an JUnit 5 Invocation Context Provider that you can use with the `@TestTemplate` annotation. This will generate a test for each interaction found for the pact files for the provider. To use it, add the `@Provider` and one of the pact source annotations to your test class (as per a JUnit 4 test), then add a method annotated with `@TestTemplate` and `@ExtendWith(PactVerificationInvocationContextProvider.class)` that takes a `PactVerificationContext` parameter. You will need to call `verifyInteraction()` on the context parameter in your test template method. For example: ```java @Provider("myAwesomeService") @PactFolder("pacts") public class ContractVerificationTest { @TestTemplate @ExtendWith(PactVerificationInvocationContextProvider.class) void pactVerificationTestTemplate(PactVerificationContext context) { context.verifyInteraction(); } } ``` For details on the provider and pact source annotations, refer to the [Pact junit runner](../pact-jvm-provider-junit/README.md) docs. ## Test target You can set the test target (the object that defines the target of the test, which should point to your provider) on the `PactVerificationContext`, but you need to do this in a before test method (annotated with `@BeforeEach`). There are three different test targets you can use: `HttpTestTarget`, `HttpsTestTarget` and `AmpqTestTarget`. For example: ```java @BeforeEach void before(PactVerificationContext context) { context.setTarget(HttpTestTarget.fromUrl(new URL(myProviderUrl))); // or something like // context.setTarget(new HttpTestTarget("localhost", myProviderPort, "/")); } ``` **Note for Maven users:** If you use Maven to run your tests, you will have to make sure that the Maven Surefire plugin is at least version 2.22.1 uses an isolated classpath. For example, configure it by adding the following to your POM: ```xml <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.22.1</version> <configuration> <useSystemClassLoader>false</useSystemClassLoader> </configuration> </plugin> ``` ## Provider State Methods Provider State Methods work in the same way as with JUnit 4 tests, refer to the [Pact junit runner](../pact-jvm-provider-junit/README.md) docs. ### Using multiple classes for the state change methods If you have a large number of state change methods, you can split things up by moving them to other classes. You will need to specify the additional classes on the test context in a `Before` method. Do this with the `withStateHandler` or `setStateHandlers` methods. See [StateAnnotationsOnAdditionalClassTest](pact-jvm-provider-junit5/src/test/java/au/com/dius/pact/provider/junit5/StateAnnotationsOnAdditionalClassTest.java) for an example. ## Modifying the requests before they are sent **Important Note:** You should only use this feature for things that can not be persisted in the pact file. By modifying the request, you are potentially modifying the contract from the consumer tests! Sometimes you may need to add things to the requests that can't be persisted in a pact file. Examples of these would be authentication tokens, which have a small life span. The Http and Https test targets support injecting the request that will executed into the test template method. You can then add things to the request before calling the `verifyInteraction()` method. For example to add a header: ```java @TestTemplate @ExtendWith(PactVerificationInvocationContextProvider.class) void testTemplate(PactVerificationContext context, HttpRequest request) { // This will add a header to the request request.addHeader("X-Auth-Token", "1234"); context.verifyInteraction(); } ``` ## Objects that can be injected into the test methods You can inject the following objects into your test methods (just like the `PactVerificationContext`). They will be null if injected before the supported phase. | Object | Can be injected from phase | Description | | ------ | --------------- | ----------- | | PactVerificationContext | @BeforeEach | The context to use to execute the interaction test | | Pact | any | The Pact model for the test | | Interaction | any | The Interaction model for the test | | HttpRequest | @TestTemplate | The request that is going to be executed (only for HTTP and HTTPS targets) | | ProviderVerifier | @TestTemplate | The verifier instance that is used to verify the interaction |

Group: au.com.dius Artifact: pact-jvm-provider-junit5_2.12
Show all versions Show documentation Show source 
 

4 downloads
Artifact pact-jvm-provider-junit5_2.12
Group au.com.dius
Version 3.6.15
Last update 29. April 2020
Organization not specified
URL https://github.com/DiUS/pact-jvm
License Apache 2
Dependencies amount 3
Dependencies pact-jvm-support, pact-jvm-provider_2.12, junit-jupiter-api,
There are maybe transitive dependencies!

pact-jvm-consumer-junit5_2.12 from group au.com.dius (version 3.6.15)

pact-jvm-consumer-junit5 ======================== JUnit 5 support for Pact consumer tests ## Dependency The library is available on maven central using: * group-id = `au.com.dius` * artifact-id = `pact-jvm-consumer-junit5_2.12` * version-id = `3.6.x` ## Usage ### 1. Add the Pact consumer test extension to the test class. To write Pact consumer tests with JUnit 5, you need to add `@ExtendWith(PactConsumerTestExt)` to your test class. This replaces the `PactRunner` used for JUnit 4 tests. The rest of the test follows a similar pattern as for JUnit 4 tests. ```java @ExtendWith(PactConsumerTestExt.class) class ExampleJavaConsumerPactTest { ``` ### 2. create a method annotated with `@Pact` that returns the interactions for the test For each test (as with JUnit 4), you need to define a method annotated with the `@Pact` annotation that returns the interactions for the test. ```java @Pact(provider="ArticlesProvider", consumer="test_consumer") public RequestResponsePact createPact(PactDslWithProvider builder) { return builder .given("test state") .uponReceiving("ExampleJavaConsumerPactTest test interaction") .path("/articles.json") .method("GET") .willRespondWith() .status(200) .body("{\"responsetest\": true}") .toPact(); } ``` ### 3. Link the mock server with the interactions for the test with `@PactTestFor` Then the final step is to use the `@PactTestFor` annotation to tell the Pact extension how to setup the Pact test. You can either put this annotation on the test class, or on the test method. For examples see [ArticlesTest](src/test/java/au/com/dius/pact/consumer/junit5/ArticlesTest.java) and [MultiTest](src/test/groovy/au/com/dius/pact/consumer/junit5/MultiTest.groovy). The `@PactTestFor` annotation allows you to control the mock server in the same way as the JUnit 4 `PactProviderRule`. It allows you to set the hostname to bind to (default is `localhost`) and the port (default is to use a random port). You can also set the Pact specification version to use (default is V3). ```java @ExtendWith(PactConsumerTestExt.class) @PactTestFor(providerName = "ArticlesProvider") public class ExampleJavaConsumerPactTest { ``` **NOTE on the hostname**: The mock server runs in the same JVM as the test, so the only valid values for hostname are: | hostname | result | | -------- | ------ | | `localhost` | binds to the address that localhost points to (normally the loopback adapter) | | `127.0.0.1` or `::1` | binds to the loopback adapter | | host name | binds to the default interface that the host machines DNS name resolves to | | `0.0.0.0` or `::` | binds to the all interfaces on the host machine | #### Matching the interactions by provider name If you set the `providerName` on the `@PactTestFor` annotation, then the first method with a `@Pact` annotation with the same provider name will be used. See [ArticlesTest](src/test/java/au/com/dius/pact/consumer/junit5/ArticlesTest.java) for an example. #### Matching the interactions by method name If you set the `pactMethod` on the `@PactTestFor` annotation, then the method with the provided name will be used (it still needs a `@Pact` annotation). See [MultiTest](src/test/groovy/au/com/dius/pact/consumer/junit5/MultiTest.groovy) for an example. ### Injecting the mock server into the test You can get the mock server injected into the test method by adding a `MockServer` parameter to the test method. ```java @Test void test(MockServer mockServer) throws IOException { HttpResponse httpResponse = Request.Get(mockServer.getUrl() + "/articles.json").execute().returnResponse(); assertThat(httpResponse.getStatusLine().getStatusCode(), is(equalTo(200))); } ``` This helps with getting the base URL of the mock server, especially when a random port is used. ## Changing the directory pact files are written to By default, pact files are written to `target/pacts` (or `build/pacts` if you use Gradle), but this can be overwritten with the `pact.rootDir` system property. This property needs to be set on the test JVM as most build tools will fork a new JVM to run the tests. For Gradle, add this to your build.gradle: ```groovy test { systemProperties['pact.rootDir'] = "$buildDir/custom-pacts-directory" } ``` For maven, use the systemPropertyVariables configuration: ```xml <project> [...] <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.18</version> <configuration> <systemPropertyVariables> <pact.rootDir>some/other/directory</pact.rootDir> <buildDirectory>${project.build.directory}</buildDirectory> [...] </systemPropertyVariables> </configuration> </plugin> </plugins> </build> [...] </project> ``` For SBT: ```scala fork in Test := true, javaOptions in Test := Seq("-Dpact.rootDir=some/other/directory") ``` ### Using `@PactFolder` annotation [3.6.2+] You can override the directory the pacts are written in a test by adding the `@PactFolder` annotation to the test class. ## Forcing pact files to be overwritten (3.6.5+) By default, when the pact file is written, it will be merged with any existing pact file. To force the file to be overwritten, set the Java system property `pact.writer.overwrite` to `true`. ## Unsupported The current implementation does not support tests with multiple providers. This will be added in a later release. # Having values injected from provider state callbacks (3.6.11+) You can have values from the provider state callbacks be injected into most places (paths, query parameters, headers, bodies, etc.). This works by using the V3 spec generators with provider state callbacks that return values. One example of where this would be useful is API calls that require an ID which would be auto-generated by the database on the provider side, so there is no way to know what the ID would be beforehand. The following DSL methods all you to set an expression that will be parsed with the values returned from the provider states: For JSON bodies, use `valueFromProviderState`.<br/> For headers, use `headerFromProviderState`.<br/> For query parameters, use `queryParameterFromProviderState`.<br/> For paths, use `pathFromProviderState`. For example, assume that an API call is made to get the details of a user by ID. A provider state can be defined that specifies that the user must be exist, but the ID will be created when the user is created. So we can then define an expression for the path where the ID will be replaced with the value returned from the provider state callback. ```java .pathFromProviderState("/api/users/${id}", "/api/users/100") ``` You can also just use the key instead of an expression: ```java .valueFromProviderState('userId', 'userId', 100) // will look value using userId as the key ```

Group: au.com.dius Artifact: pact-jvm-consumer-junit5_2.12
Show all versions Show documentation Show source 
 

3 downloads
Artifact pact-jvm-consumer-junit5_2.12
Group au.com.dius
Version 3.6.15
Last update 29. April 2020
Organization not specified
URL https://github.com/DiUS/pact-jvm
License Apache 2
Dependencies amount 2
Dependencies pact-jvm-consumer_2.12, junit-jupiter-api,
There are maybe transitive dependencies!

pact-jvm-provider-junit5 from group au.com.dius (version 4.0.10)

# Pact Junit 5 Extension ## Overview For writing Pact verification tests with JUnit 5, there is an JUnit 5 Invocation Context Provider that you can use with the `@TestTemplate` annotation. This will generate a test for each interaction found for the pact files for the provider. To use it, add the `@Provider` and one of the pact source annotations to your test class (as per a JUnit 4 test), then add a method annotated with `@TestTemplate` and `@ExtendWith(PactVerificationInvocationContextProvider.class)` that takes a `PactVerificationContext` parameter. You will need to call `verifyInteraction()` on the context parameter in your test template method. For example: ```java @Provider("myAwesomeService") @PactFolder("pacts") public class ContractVerificationTest { @TestTemplate @ExtendWith(PactVerificationInvocationContextProvider.class) void pactVerificationTestTemplate(PactVerificationContext context) { context.verifyInteraction(); } } ``` For details on the provider and pact source annotations, refer to the [Pact junit runner](../pact-jvm-provider-junit/README.md) docs. ## Test target You can set the test target (the object that defines the target of the test, which should point to your provider) on the `PactVerificationContext`, but you need to do this in a before test method (annotated with `@BeforeEach`). There are three different test targets you can use: `HttpTestTarget`, `HttpsTestTarget` and `AmpqTestTarget`. For example: ```java @BeforeEach void before(PactVerificationContext context) { context.setTarget(HttpTestTarget.fromUrl(new URL(myProviderUrl))); // or something like // context.setTarget(new HttpTestTarget("localhost", myProviderPort, "/")); } ``` **Note for Maven users:** If you use Maven to run your tests, you will have to make sure that the Maven Surefire plugin is at least version 2.22.1 uses an isolated classpath. For example, configure it by adding the following to your POM: ```xml <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.22.1</version> <configuration> <useSystemClassLoader>false</useSystemClassLoader> </configuration> </plugin> ``` ## Provider State Methods Provider State Methods work in the same way as with JUnit 4 tests, refer to the [Pact junit runner](../pact-jvm-provider-junit/README.md) docs. ### Using multiple classes for the state change methods If you have a large number of state change methods, you can split things up by moving them to other classes. You will need to specify the additional classes on the test context in a `Before` method. Do this with the `withStateHandler` or `setStateHandlers` methods. See [StateAnnotationsOnAdditionalClassTest](src/test/java/au/com/dius/pact/provider/junit5/StateAnnotationsOnAdditionalClassTest.java) for an example. ## Modifying the requests before they are sent **Important Note:** You should only use this feature for things that can not be persisted in the pact file. By modifying the request, you are potentially modifying the contract from the consumer tests! Sometimes you may need to add things to the requests that can't be persisted in a pact file. Examples of these would be authentication tokens, which have a small life span. The Http and Https test targets support injecting the request that will executed into the test template method. You can then add things to the request before calling the `verifyInteraction()` method. For example to add a header: ```java @TestTemplate @ExtendWith(PactVerificationInvocationContextProvider.class) void testTemplate(PactVerificationContext context, HttpRequest request) { // This will add a header to the request request.addHeader("X-Auth-Token", "1234"); context.verifyInteraction(); } ``` ## Objects that can be injected into the test methods You can inject the following objects into your test methods (just like the `PactVerificationContext`). They will be null if injected before the supported phase. | Object | Can be injected from phase | Description | | ------ | --------------- | ----------- | | PactVerificationContext | @BeforeEach | The context to use to execute the interaction test | | Pact | any | The Pact model for the test | | Interaction | any | The Interaction model for the test | | HttpRequest | @TestTemplate | The request that is going to be executed (only for HTTP and HTTPS targets) | | ProviderVerifier | @TestTemplate | The verifier instance that is used to verify the interaction | ## Allowing the test to pass when no pacts are found to verify (version 4.0.7+) By default, the test will fail with an exception if no pacts were found to verify. This can be overridden by adding the `@IgnoreNoPactsToVerify` annotation to the test class. For this to work, you test class will need to be able to receive null values for any of the injected parameters.

Group: au.com.dius Artifact: pact-jvm-provider-junit5
Show all versions Show documentation Show source 
 

0 downloads
Artifact pact-jvm-provider-junit5
Group au.com.dius
Version 4.0.10
Last update 18. April 2020
Organization not specified
URL https://github.com/DiUS/pact-jvm
License Apache 2
Dependencies amount 3
Dependencies junit-jupiter-api, pact-jvm-core-support, pact-jvm-provider,
There are maybe transitive dependencies!

pact-jvm-consumer-junit5 from group au.com.dius (version 4.0.10)

pact-jvm-consumer-junit5 ======================== JUnit 5 support for Pact consumer tests ## Dependency The library is available on maven central using: * group-id = `au.com.dius` * artifact-id = `pact-jvm-consumer-junit5` * version-id = `4.0.x` ## Usage ### 1. Add the Pact consumer test extension to the test class. To write Pact consumer tests with JUnit 5, you need to add `@ExtendWith(PactConsumerTestExt)` to your test class. This replaces the `PactRunner` used for JUnit 4 tests. The rest of the test follows a similar pattern as for JUnit 4 tests. ```java @ExtendWith(PactConsumerTestExt.class) class ExampleJavaConsumerPactTest { ``` ### 2. create a method annotated with `@Pact` that returns the interactions for the test For each test (as with JUnit 4), you need to define a method annotated with the `@Pact` annotation that returns the interactions for the test. ```java @Pact(provider="ArticlesProvider", consumer="test_consumer") public RequestResponsePact createPact(PactDslWithProvider builder) { return builder .given("test state") .uponReceiving("ExampleJavaConsumerPactTest test interaction") .path("/articles.json") .method("GET") .willRespondWith() .status(200) .body("{\"responsetest\": true}") .toPact(); } ``` ### 3. Link the mock server with the interactions for the test with `@PactTestFor` Then the final step is to use the `@PactTestFor` annotation to tell the Pact extension how to setup the Pact test. You can either put this annotation on the test class, or on the test method. For examples see [ArticlesTest](src/test/java/au/com/dius/pact/consumer/junit5/ArticlesTest.java) and [MultiTest](src/test/groovy/au/com/dius/pact/consumer/junit5/MultiTest.groovy). The `@PactTestFor` annotation allows you to control the mock server in the same way as the JUnit 4 `PactProviderRule`. It allows you to set the hostname to bind to (default is `localhost`) and the port (default is to use a random port). You can also set the Pact specification version to use (default is V3). ```java @ExtendWith(PactConsumerTestExt.class) @PactTestFor(providerName = "ArticlesProvider") public class ExampleJavaConsumerPactTest { ``` **NOTE on the hostname**: The mock server runs in the same JVM as the test, so the only valid values for hostname are: | hostname | result | | -------- | ------ | | `localhost` | binds to the address that localhost points to (normally the loopback adapter) | | `127.0.0.1` or `::1` | binds to the loopback adapter | | host name | binds to the default interface that the host machines DNS name resolves to | | `0.0.0.0` or `::` | binds to the all interfaces on the host machine | #### Matching the interactions by provider name If you set the `providerName` on the `@PactTestFor` annotation, then the first method with a `@Pact` annotation with the same provider name will be used. See [ArticlesTest](src/test/java/au/com/dius/pact/consumer/junit5/ArticlesTest.java) for an example. #### Matching the interactions by method name If you set the `pactMethod` on the `@PactTestFor` annotation, then the method with the provided name will be used (it still needs a `@Pact` annotation). See [MultiTest](src/test/groovy/au/com/dius/pact/consumer/junit5/MultiTest.groovy) for an example. ### Injecting the mock server into the test You can get the mock server injected into the test method by adding a `MockServer` parameter to the test method. ```java @Test void test(MockServer mockServer) throws IOException { HttpResponse httpResponse = Request.Get(mockServer.getUrl() + "/articles.json").execute().returnResponse(); assertThat(httpResponse.getStatusLine().getStatusCode(), is(equalTo(200))); } ``` This helps with getting the base URL of the mock server, especially when a random port is used. ## Changing the directory pact files are written to By default, pact files are written to `target/pacts` (or `build/pacts` if you use Gradle), but this can be overwritten with the `pact.rootDir` system property. This property needs to be set on the test JVM as most build tools will fork a new JVM to run the tests. For Gradle, add this to your build.gradle: ```groovy test { systemProperties['pact.rootDir'] = "$buildDir/custom-pacts-directory" } ``` For maven, use the systemPropertyVariables configuration: ```xml <project> [...] <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.18</version> <configuration> <systemPropertyVariables> <pact.rootDir>some/other/directory</pact.rootDir> <buildDirectory>${project.build.directory}</buildDirectory> [...] </systemPropertyVariables> </configuration> </plugin> </plugins> </build> [...] </project> ``` For SBT: ```scala fork in Test := true, javaOptions in Test := Seq("-Dpact.rootDir=some/other/directory") ``` ### Using `@PactFolder` annotation You can override the directory the pacts are written in a test by adding the `@PactFolder` annotation to the test class. ## Forcing pact files to be overwritten (3.6.5+) By default, when the pact file is written, it will be merged with any existing pact file. To force the file to be overwritten, set the Java system property `pact.writer.overwrite` to `true`. ## Unsupported The current implementation does not support tests with multiple providers. This will be added in a later release. # Having values injected from provider state callbacks (3.6.11+) You can have values from the provider state callbacks be injected into most places (paths, query parameters, headers, bodies, etc.). This works by using the V3 spec generators with provider state callbacks that return values. One example of where this would be useful is API calls that require an ID which would be auto-generated by the database on the provider side, so there is no way to know what the ID would be beforehand. The following DSL methods all you to set an expression that will be parsed with the values returned from the provider states: For JSON bodies, use `valueFromProviderState`.<br/> For headers, use `headerFromProviderState`.<br/> For query parameters, use `queryParameterFromProviderState`.<br/> For paths, use `pathFromProviderState`. For example, assume that an API call is made to get the details of a user by ID. A provider state can be defined that specifies that the user must be exist, but the ID will be created when the user is created. So we can then define an expression for the path where the ID will be replaced with the value returned from the provider state callback. ```java .pathFromProviderState("/api/users/${id}", "/api/users/100") ``` You can also just use the key instead of an expression: ```java .valueFromProviderState('userId', 'userId', 100) // will look value using userId as the key ```

Group: au.com.dius Artifact: pact-jvm-consumer-junit5
Show all versions Show documentation Show source 
 

0 downloads
Artifact pact-jvm-consumer-junit5
Group au.com.dius
Version 4.0.10
Last update 18. April 2020
Organization not specified
URL https://github.com/DiUS/pact-jvm
License Apache 2
Dependencies amount 2
Dependencies junit-jupiter-api, pact-jvm-consumer,
There are maybe transitive dependencies!

pact-jvm-provider-spring_2.11 from group au.com.dius (version 3.5.24)

# Pact Spring/JUnit runner ## Overview Library provides ability to play contract tests against a provider using Spring & JUnit. This library is based on and references the JUnit package, so see [junit provider support](pact-jvm-provider-junit) for more details regarding configuration using JUnit. Supports: - Standard ways to load pacts from folders and broker - Easy way to change assertion strategy - Spring Test MockMVC Controllers and ControllerAdvice using MockMvc standalone setup. - MockMvc debugger output - Multiple @State runs to test a particular Provider State multiple times - **au.com.dius.pact.provider.junit.State** custom annotation - before each interaction that requires a state change, all methods annotated by `@State` with appropriate the state listed will be invoked. **NOTE:** For publishing provider verification results to a pact broker, make sure the Java system property `pact.provider.version` is set with the version of your provider. ## Example of MockMvc test ```java @RunWith(RestPactRunner.class) // Custom pact runner, child of PactRunner which runs only REST tests @Provider("myAwesomeService") // Set up name of tested provider @PactFolder("pacts") // Point where to find pacts (See also section Pacts source in documentation) public class ContractTest { //Create an instance of your controller. We cannot autowire this as we're not using (and don't want to use) a Spring test runner. @InjectMocks private AwesomeController awesomeController = new AwesomeController(); //Mock your service logic class. We'll use this to create scenarios for respective provider states. @Mock private AwesomeBusinessLogic awesomeBusinessLogic; //Create an instance of your controller advice (if you have one). This will be passed to the MockMvcTarget constructor to be wired up with MockMvc. @InjectMocks private AwesomeControllerAdvice awesomeControllerAdvice = new AwesomeControllerAdvice(); //Create a new instance of the MockMvcTarget and annotate it as the TestTarget for PactRunner @TestTarget public final MockMvcTarget target = new MockMvcTarget(); @Before //Method will be run before each test of interaction public void before() { //initialize your mocks using your mocking framework MockitoAnnotations.initMocks(this); //configure the MockMvcTarget with your controller and controller advice target.setControllers(awesomeController); target.setControllerAdvice(awesomeControllerAdvice); } @State("default", "no-data") // Method will be run before testing interactions that require "default" or "no-data" state public void toDefaultState() { target.setRunTimes(3); //let's loop through this state a few times for a 3 data variants when(awesomeBusinessLogic.getById(any(UUID.class))) .thenReturn(myTestHelper.generateRandomReturnData(UUID.randomUUID(), ExampleEnum.ONE)) .thenReturn(myTestHelper.generateRandomReturnData(UUID.randomUUID(), ExampleEnum.TWO)) .thenReturn(myTestHelper.generateRandomReturnData(UUID.randomUUID(), ExampleEnum.THREE)); } @State("error-case") public void SingleUploadExistsState_Success() { target.setRunTimes(1); //tell the runner to only loop one time for this state //you might want to throw exceptions to be picked off by your controller advice when(awesomeBusinessLogic.getById(any(UUID.class))) .then(i -> { throw new NotCoolException(i.getArgumentAt(0, UUID.class).toString()); }); } } ``` ## Using a Spring runner (version 3.5.7+) You can use `SpringRestPactRunner` instead of the default Pact runner to use the Spring test annotations. This will allow you to inject or mock spring beans. For example: ```java @RunWith(SpringRestPactRunner.class) @Provider("pricing") @PactBroker(protocol = "https", host = "${pactBrokerHost}", port = "443", authentication = @PactBrokerAuth(username = "${pactBrokerUser}", password = "${pactBrokerPassword}")) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) public class PricingServiceProviderPactTest { @MockBean private ProductClient productClient; // This will replace the bean with a mock in the application context @TestTarget @SuppressWarnings(value = "VisibilityModifier") public final Target target = new HttpTarget(8091); @State("Product X010000021 exists") public void setupProductX010000021() throws IOException { reset(productClient); ProductBuilder product = new ProductBuilder() .withProductCode("X010000021"); when(productClient.fetch((Set<String>) argThat(contains("X010000021")), any())).thenReturn(product); } @State("the product code X00001 can be priced") public void theProductCodeX00001CanBePriced() throws IOException { reset(productClient); ProductBuilder product = new ProductBuilder() .withProductCode("X00001"); when(productClient.find((Set<String>) argThat(contains("X00001")), any())).thenReturn(product); } } ``` ### Using Spring Context Properties (version 3.5.14+) From version 3.5.14 onwards, the SpringRestPactRunner will look up any annotation expressions (like `${pactBrokerHost}`) above) from the Spring context. For Springboot, this will allow you to define the properties in the application test properties. For instance, if you create the following `application.yml` in the test resources: ```yaml pactbroker: host: "your.broker.local" port: "443" protocol: "https" auth: username: "<your broker username>" password: "<your broker password>" ``` Then you can use the defaults on the `@PactBroker` annotation. ```java @RunWith(SpringRestPactRunner.class) @Provider("My Service") @PactBroker( authentication = @PactBrokerAuth(username = "${pactbroker.auth.username}", password = "${pactbroker.auth.password}") ) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class PactVerificationTest { ``` ### Using a random port with a Springboot test (version 3.5.14+) If you use a random port in a springboot test (by setting `SpringBootTest.WebEnvironment.RANDOM_PORT`), you can use the `SpringBootHttpTarget` which will get the application port from the spring application context. For example: ```java @RunWith(SpringRestPactRunner.class) @Provider("My Service") @PactBroker @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class PactVerificationTest { @TestTarget public final Target target = new SpringBootHttpTarget(); } ```

Group: au.com.dius Artifact: pact-jvm-provider-spring_2.11
Show all versions Show documentation Show source 
 

2 downloads
Artifact pact-jvm-provider-spring_2.11
Group au.com.dius
Version 3.5.24
Last update 04. November 2018
Organization not specified
URL https://github.com/DiUS/pact-jvm
License Apache 2
Dependencies amount 13
Dependencies kotlin-stdlib-jdk8, kotlin-reflect, slf4j-api, groovy-all, kotlin-logging, scala-library, scala-logging_2.11, pact-jvm-provider-junit_2.11, spring-boot-starter-test, spring-web, spring-webmvc, javax.servlet-api, jackson-datatype-joda,
There are maybe transitive dependencies!

pact-jvm-provider-spring from group au.com.dius (version 4.0.10)

# Pact Spring/JUnit runner ## Overview Library provides ability to play contract tests against a provider using Spring & JUnit. This library is based on and references the JUnit package, so see the [Pact JUnit 4](../pact-jvm-provider-junit) or [Pact JUnit 5](../pact-jvm-provider-junit5) providers for more details regarding configuration using JUnit. Supports: - Standard ways to load pacts from folders and broker - Easy way to change assertion strategy - Spring Test MockMVC Controllers and ControllerAdvice using MockMvc standalone setup. - MockMvc debugger output - Multiple @State runs to test a particular Provider State multiple times - **au.com.dius.pact.provider.junit.State** custom annotation - before each interaction that requires a state change, all methods annotated by `@State` with appropriate the state listed will be invoked. **NOTE:** For publishing provider verification results to a pact broker, make sure the Java system property `pact.provider.version` is set with the version of your provider. ## Example of MockMvc test ```java @RunWith(RestPactRunner.class) // Custom pact runner, child of PactRunner which runs only REST tests @Provider("myAwesomeService") // Set up name of tested provider @PactFolder("pacts") // Point where to find pacts (See also section Pacts source in documentation) public class ContractTest { //Create an instance of your controller. We cannot autowire this as we're not using (and don't want to use) a Spring test runner. @InjectMocks private AwesomeController awesomeController = new AwesomeController(); //Mock your service logic class. We'll use this to create scenarios for respective provider states. @Mock private AwesomeBusinessLogic awesomeBusinessLogic; //Create an instance of your controller advice (if you have one). This will be passed to the MockMvcTarget constructor to be wired up with MockMvc. @InjectMocks private AwesomeControllerAdvice awesomeControllerAdvice = new AwesomeControllerAdvice(); //Create a new instance of the MockMvcTarget and annotate it as the TestTarget for PactRunner @TestTarget public final MockMvcTarget target = new MockMvcTarget(); @Before //Method will be run before each test of interaction public void before() { //initialize your mocks using your mocking framework MockitoAnnotations.initMocks(this); //configure the MockMvcTarget with your controller and controller advice target.setControllers(awesomeController); target.setControllerAdvice(awesomeControllerAdvice); } @State("default", "no-data") // Method will be run before testing interactions that require "default" or "no-data" state public void toDefaultState() { target.setRunTimes(3); //let's loop through this state a few times for a 3 data variants when(awesomeBusinessLogic.getById(any(UUID.class))) .thenReturn(myTestHelper.generateRandomReturnData(UUID.randomUUID(), ExampleEnum.ONE)) .thenReturn(myTestHelper.generateRandomReturnData(UUID.randomUUID(), ExampleEnum.TWO)) .thenReturn(myTestHelper.generateRandomReturnData(UUID.randomUUID(), ExampleEnum.THREE)); } @State("error-case") public void SingleUploadExistsState_Success() { target.setRunTimes(1); //tell the runner to only loop one time for this state //you might want to throw exceptions to be picked off by your controller advice when(awesomeBusinessLogic.getById(any(UUID.class))) .then(i -> { throw new NotCoolException(i.getArgumentAt(0, UUID.class).toString()); }); } } ``` ## Using Spring runners You can use `SpringRestPactRunner` or `SpringMessagePactRunner` instead of the default Pact runner to use the Spring test annotations. This will allow you to inject or mock spring beans. `SpringRestPactRunner` is for restful webapps and `SpringMessagePactRunner` is for async message tests. For example: ```java @RunWith(SpringRestPactRunner.class) @Provider("pricing") @PactBroker(protocol = "https", host = "${pactBrokerHost}", port = "443", authentication = @PactBrokerAuth(username = "${pactBrokerUser}", password = "${pactBrokerPassword}")) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) public class PricingServiceProviderPactTest { @MockBean private ProductClient productClient; // This will replace the bean with a mock in the application context @TestTarget @SuppressWarnings(value = "VisibilityModifier") public final Target target = new HttpTarget(8091); @State("Product X010000021 exists") public void setupProductX010000021() throws IOException { reset(productClient); ProductBuilder product = new ProductBuilder() .withProductCode("X010000021"); when(productClient.fetch((Set<String>) argThat(contains("X010000021")), any())).thenReturn(product); } @State("the product code X00001 can be priced") public void theProductCodeX00001CanBePriced() throws IOException { reset(productClient); ProductBuilder product = new ProductBuilder() .withProductCode("X00001"); when(productClient.find((Set<String>) argThat(contains("X00001")), any())).thenReturn(product); } } ``` ### Using Spring Context Properties The SpringRestPactRunner will look up any annotation expressions (like `${pactBrokerHost}`) above) from the Spring context. For Springboot, this will allow you to define the properties in the application test properties. For instance, if you create the following `application.yml` in the test resources: ```yaml pactbroker: host: "your.broker.local" port: "443" protocol: "https" auth: username: "<your broker username>" password: "<your broker password>" ``` Then you can use the defaults on the `@PactBroker` annotation. ```java @RunWith(SpringRestPactRunner.class) @Provider("My Service") @PactBroker( authentication = @PactBrokerAuth(username = "${pactbroker.auth.username}", password = "${pactbroker.auth.password}") ) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class PactVerificationTest { ``` ### Using a random port with a Springboot test If you use a random port in a springboot test (by setting `SpringBootTest.WebEnvironment.RANDOM_PORT`), you need to set it to the `TestTarget`. How this works is different for JUnit4 and JUnit5. #### JUnit4 You can use the `SpringBootHttpTarget` which will get the application port from the spring application context. For example: ```java @RunWith(SpringRestPactRunner.class) @Provider("My Service") @PactBroker @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class PactVerificationTest { @TestTarget public final Target target = new SpringBootHttpTarget(); } ``` #### JUnit5 You actually don't need to dependend on `pact-jvm-provider-spring` for this. It's sufficient to depend on `pact-jvm-provider-junit5`. You can set the port to the `HttpTestTarget` object in the before method. ```java @Provider("My Service") @PactBroker @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class PactVerificationTest { @LocalServerPort private int port; @BeforeEach void before(PactVerificationContext context) { context.setTarget(new HttpTestTarget("localhost", port)); } } ```

Group: au.com.dius Artifact: pact-jvm-provider-spring
Show all versions Show documentation Show source 
 

0 downloads
Artifact pact-jvm-provider-spring
Group au.com.dius
Version 4.0.10
Last update 18. April 2020
Organization not specified
URL https://github.com/DiUS/pact-jvm
License Apache 2
Dependencies amount 5
Dependencies spring-boot-starter-test, spring-webmvc, javax.servlet-api, jackson-datatype-joda, pact-jvm-provider-junit,
There are maybe transitive dependencies!

pact-jvm-provider-junit_2.11 from group au.com.dius (version 3.5.24)

# Pact junit runner ## Overview Library provides ability to play contract tests against a provider service in JUnit fashionable way. Supports: - Out-of-the-box convenient ways to load pacts - Easy way to change assertion strategy - **org.junit.BeforeClass**, **org.junit.AfterClass** and **org.junit.ClassRule** JUnit annotations, that will be run once - before/after whole contract test suite. - **org.junit.Before**, **org.junit.After** and **org.junit.Rule** JUnit annotations, that will be run before/after each test of an interaction. - **au.com.dius.pact.provider.junit.State** custom annotation - before each interaction that requires a state change, all methods annotated by `@State` with appropriate the state listed will be invoked. These methods must either take no parameters or a single Map parameter. ## Example of HTTP test ```java @RunWith(PactRunner.class) // Say JUnit to run tests with custom Runner @Provider("myAwesomeService") // Set up name of tested provider @PactFolder("pacts") // Point where to find pacts (See also section Pacts source in documentation) public class ContractTest { // NOTE: this is just an example of embedded service that listens to requests, you should start here real service @ClassRule //Rule will be applied once: before/after whole contract test suite public static final ClientDriverRule embeddedService = new ClientDriverRule(8332); @BeforeClass //Method will be run once: before whole contract test suite public static void setUpService() { //Run DB, create schema //Run service //... } @Before //Method will be run before each test of interaction public void before() { // Rest data // Mock dependent service responses // ... embeddedService.addExpectation( onRequestTo("/data"), giveEmptyResponse() ); } @State("default", "no-data") // Method will be run before testing interactions that require "default" or "no-data" state public void toDefaultState() { // Prepare service before interaction that require "default" state // ... System.out.println("Now service in default state"); } @State("with-data") // Method will be run before testing interactions that require "with-data" state public void toStateWithData(Map data) { // Prepare service before interaction that require "with-data" state. The provider state data will be passed // in the data parameter // ... System.out.println("Now service in state using data " + data); } @TestTarget // Annotation denotes Target that will be used for tests public final Target target = new HttpTarget(8332); // Out-of-the-box implementation of Target (for more information take a look at Test Target section) } ``` ## Example of AMQP Message test ```java @RunWith(PactRunner.class) // Say JUnit to run tests with custom Runner @Provider("myAwesomeService") // Set up name of tested provider @PactBroker(host="pactbroker", port = "80") public class ConfirmationKafkaContractTest { @TestTarget // Annotation denotes Target that will be used for tests public final Target target = new AmqpTarget(); // Out-of-the-box implementation of Target (for more information take a look at Test Target section) @BeforeClass //Method will be run once: before whole contract test suite public static void setUpService() { //Run DB, create schema //Run service //... } @Before //Method will be run before each test of interaction public void before() { // Message data preparation // ... } @PactVerifyProvider('an order confirmation message') String verifyMessageForOrder() { Order order = new Order() order.setId(10000004) order.setPrice(BigDecimal.TEN) order.setUnits(15) def message = new ConfirmationKafkaMessageBuilder() .withOrder(order) .build() JsonOutput.toJson(message) } } ``` ## Provider state callback methods For the provider states in the pact being verified, you can define methods to be invoked to setup the correct state for each interaction. Just annotate a method with the `au.com.dius.pact.provider.junit.State` annotation and the method will be invoked before the interaction is verified. For example: ```java @State("SomeProviderState") // Must match the state description in the pact file public void someProviderState() { // Do what you need to set the correct state } ``` If there are parameters in the pact file, just add a Map parameter to the method to be able to access those parameters. ```java @State("SomeProviderState") public void someProviderState(Map<String, Object> providerStateParameters) { // Do what you need to set the correct state } ``` ### Provider state teardown methods [3.5.22+] If you need to tear down your provider state, you can annotate a method with the `@State` annotation with the action set to `StateChangeAction.TEARDOWN` and it will be invoked after the interaction is verified. ```java @State("SomeProviderState", action = StateChangeAction.TEARDOWN) public void someProviderStateCleanup() { // Do what you need to to teardown the state } ``` ## Pact source The Pact runner will automatically collect pacts based on annotations on the test class. For this purpose there are 3 out-of-the-box options (files from a directory, files from a set of URLs or a pact broker) or you can easily add your own Pact source. If you need to load a single pact file from the file system, use the `PactUrl` with the URL set to the file path. **Note:** You can only define one source of pacts per test class. ### Download pacts from a pact-broker To use pacts from a Pact Broker, annotate the test class with `@PactBroker(host="host.of.pact.broker.com", port = "80")`. From _version 3.2.2/2.4.3+_ you can also specify the protocol, which defaults to "http". The pact broker will be queried for all pacts with the same name as the provider annotation. For example, test all pacts for the "Activity Service" in the pact broker: ```java @RunWith(PactRunner.class) @Provider("Activity Service") @PactBroker(host = "localhost", port = "80") public class PactJUnitTest { @TestTarget public final Target target = new HttpTarget(5050); } ``` #### _Version 3.2.3/2.4.4+_ - Using Java System properties The pact broker loader was updated to allow system properties to be used for the hostname, port or protocol. The port was changed to a string to allow expressions to be set. To use a system property or environment variable, you can place the property name in `${}` expression de-markers: ```java @PactBroker(host="${pactbroker.hostname}", port = "80") ``` You can provide a default value by separating the property name with a colon (`:`): ```java @PactBroker(host="${pactbroker.hostname:localhost}", port = "80") ``` #### _Version 3.5.3+_ - More Java System properties The default values of the `@PactBroker` annotation now enable variable interpolation. The following keys may be managed through the environment * `pactbroker.host` * `pactbroker.port` * `pactbroker.protocol` * `pactbroker.tags` (comma separated) * `pactbroker.auth.scheme` * `pactbroker.auth.username` * `pactbroker.auth.password` #### _Version 3.2.4/2.4.6+_ - Using tags with the pact broker The pact broker allows different versions to be tagged. To load all the pacts: ```java @PactBroker(host="pactbroker", port = "80", tags = {"latest", "dev", "prod"}) ``` The default value for tags is `latest` which is not actually a tag but instead corresponds to the latest version ignoring the tags. If there are multiple consumers matching the name specified in the provider annotation then the latest pact for each of the consumers is loaded. For any other value the latest pact tagged with the specified tag is loaded. Specifying multiple tags is an OR operation. For example if you specify `tags = {"dev", "prod"}` then both the latest pact file tagged with `dev` and the latest pact file taggged with `prod` is loaded. #### _Version 3.3.4/2.4.19+_ - Using basic auth with the with the pact broker You can use basic authentication with the `@PactBroker` annotation by setting the `authentication` value to a `@PactBrokerAuth` annotation. For example: ```java @PactBroker(host = "${pactbroker.url:localhost}", port = "1234", tags = {"latest", "prod", "dev"}, authentication = @PactBrokerAuth(username = "test", password = "test")) ``` The `username` and `password` values also take Java system property expressions. ### Pact Url To use pacts from urls annotate the test class with ```java @PactUrl(urls = {"http://build.server/zoo_app-animal_service.json"} ) ``` If you need to load a single pact file from the file system, you can use the `PactUrl` with the URL set to the file path. ### Pact folder To use pacts from a resource folder of the project annotate test class with ```java @PactFolder("subfolder/in/resource/directory") ``` ### Custom pacts source It's possible to use a custom Pact source. For this, implement interface `au.com.dius.pact.provider.junit.loader.PactLoader` and annotate the test class with `@PactSource(MyOwnPactLoader.class)`. **Note:** class `MyOwnPactLoader` must have a default empty constructor or a constructor with one argument of class `Class` which at runtime will be the test class so you can get custom annotations of test class. ### Filtering the interactions that are verified [version 3.5.3+] By default, the pact runner will verify all pacts for the given provider. You can filter the pacts and interactions by the following methods. #### Filtering by Consumer You can run only those pacts for a particular consumer by adding a `@Consumer` annotation to the test class. For example: ```java @RunWith(PactRunner.class) @Provider("Activity Service") @Consumer("Activity Consumer") @PactBroker(host = "localhost", port = "80") public class PactJUnitTest { @TestTarget public final Target target = new HttpTarget(5050); } ``` #### Filtering by Provider State You can filter the interactions that are executed by adding a `@PactFilter` annotation to your test class. The pact filter annotation will then only verify interactions that have a matching provider state. You can provide multiple states to match with. For example: ```java @RunWith(PactRunner.class) @Provider("Activity Service") @PactBroker(host = "localhost", port = "80") @PactFilter('Activity 100 exists in the database') public class PactJUnitTest { @TestTarget public final Target target = new HttpTarget(5050); } ``` You can also use regular expressions with the filter [version 3.5.3+]. For example: ```java @RunWith(PactRunner.class) @PactFilter('Activity \\d+ exists in the database') public class PactJUnitTest { } ``` ### Setting the test to not fail when no pacts are found [version 3.5.3+] By default the pact runner will fail the verification test if no pact files are found to verify. To change the failure into a warning, add a `@IgnoreNoPactsToVerify` annotation to your test class. #### Ignoring IO errors loading pact files [version 3.5.24+] You can also set the test to ignore any IO and parser exceptions when loading the pact files by setting the `ignoreIoErrors` attribute on the annotation to `"true"` or setting the JVM system property `pact.verification.ignoreIoErrors` to `true`. ** WARNING! Do not enable this on your CI server, as this could result in your build passing with no providers having been verified due to a configuration error. ** ## Test target The field in test class of type `au.com.dius.pact.provider.junit.target.Target` annotated with `au.com.dius.pact.provider.junit.target.TestTarget` will be used for actual Interaction execution and asserting of contract. **Note:** there must be exactly 1 such field, otherwise an `InitializationException` will be thrown. ### HttpTarget `au.com.dius.pact.provider.junit.target.HttpTarget` - out-of-the-box implementation of `au.com.dius.pact.provider.junit.target.Target` that will play pacts as http request and assert response from service by matching rules from pact. _Version 3.2.2/2.4.3+_ you can also specify the protocol, defaults to "http". ### AmqpTarget `au.com.dius.pact.provider.junit.target.AmqpTarget` - out-of-the-box implementation of `au.com.dius.pact.provider.junit.target.Target` that will play pacts as an AMQP message and assert response from service by matching rules from pact. #### Modifying the requests before they are sent [Version 3.2.3/2.4.5+] Sometimes you may need to add things to the requests that can't be persisted in a pact file. Examples of these would be authentication tokens, which have a small life span. The HttpTarget supports request filters by annotating methods on the test class with `@TargetRequestFilter`. These methods must be public void methods that take a single HttpRequest parameter. For example: ```java @TargetRequestFilter public void exampleRequestFilter(HttpRequest request) { request.addHeader("Authorization", "OAUTH hdsagasjhgdjashgdah..."); } ``` __*Important Note:*__ You should only use this feature for things that can not be persisted in the pact file. By modifying the request, you are potentially modifying the contract from the consumer tests! #### Turning off URL decoding of the paths in the pact file [version 3.3.3+] By default the paths loaded from the pact file will be decoded before the request is sent to the provider. To turn this behaviour off, set the system property `pact.verifier.disableUrlPathDecoding` to `true`. __*Important Note:*__ If you turn off the url path decoding, you need to ensure that the paths in the pact files are correctly encoded. The verifier will not be able to make a request with an invalid encoded path. ### Custom Test Target It's possible to use custom `Target`, for that interface `Target` should be implemented and this class can be used instead of `HttpTarget`. # Verification Reports [versions 3.2.7/2.4.9+] The default test behaviour is to display the verification being done to the console, and pass or fail the test via the normal JUnit mechanism. From versions 3.2.7/2.4.9+, additional reports can be generated from the tests. ## Enabling additional reports via annotations on the test classes A `@VerificationReports` annotation can be added to any pact test class which will control the verification output. The annotation takes a list report types and an optional report directory (defaults to "target/pact/reports"). The currently supported report types are `console`, `markdown` and `json`. For example: ```java @VerificationReports({"console", "markdown"}) public class MyPactTest { ``` will enable the markdown report in addition to the normal console output. And, ```java @VerificationReports(value = {"markdown"}, reportDir = "/myreports") public class MyPactTest { ``` will disable the normal console output and write the markdown reports to "/myreports". ## Enabling additional reports via Java system properties or environment variables The additional reports can also be enabled with Java System properties or environment variables. The following two properties have been introduced: `pact.verification.reports` and `pact.verification.reportDir`. `pact.verification.reports` is the comma separated list of report types to enable (e.g. `console,json,markdown`). `pact.verification.reportDir` is the directory to write reports to (defaults to "target/pact/reports"). ## Additional Reports The following report types are available in addition to console output (`console`, which is enabled by default): `markdown`, `json`. You can also provide a fully qualified classname as report so custom reports are also supported. This class must implement `au.com.dius.pact.provider.reporters.VerifierReporter` interface in order to be correct custom implementation of a report. # Publishing verification results to a Pact Broker [version 3.5.4+] For pacts that are loaded from a Pact Broker, the results of running the verification can be published back to the broker against the URL for the pact. You will be able to see the result on the Pact Broker home screen. You need to set the version of the provider that is verified using the `pact.provider.version` system property. To enable publishing of results, set the property `pact.verifier.publishResults` to `true` [version 3.5.18+].

Group: au.com.dius Artifact: pact-jvm-provider-junit_2.11
Show all versions Show documentation Show source 
 

9 downloads
Artifact pact-jvm-provider-junit_2.11
Group au.com.dius
Version 3.5.24
Last update 04. November 2018
Organization not specified
URL https://github.com/DiUS/pact-jvm
License Apache 2
Dependencies amount 15
Dependencies kotlin-stdlib-jdk8, kotlin-reflect, slf4j-api, groovy-all, kotlin-logging, scala-library, scala-logging_2.11, pact-jvm-provider_2.11, fluent-hc, httpclient, junit, commons-lang3, jool, guava-retrying, mail,
There are maybe transitive dependencies!



Page 1 from 2 (items total 15)


© 2015 - 2024 Weber Informatics LLC | Privacy Policy