Download JAR files tagged by target with all dependencies
gwt-method-inject from group net.wetheinter (version 2.5.1)
Artifact gwt-method-inject
Group net.wetheinter
Version 2.5.1
Last update 23. February 2014
Organization not specified
URL Not specified
License not specified
Dependencies amount 0
Dependencies No dependencies
There are maybe transitive dependencies!
Group net.wetheinter
Version 2.5.1
Last update 23. February 2014
Organization not specified
URL Not specified
License not specified
Dependencies amount 0
Dependencies No dependencies
There are maybe transitive dependencies!
specs2_2.13 from group au.com.dius.pact.consumer (version 4.2.21)
pact-jvm-consumer-specs2
========================
## Specs2 Bindings for the pact-jvm library
## Dependency
In the root folder of your project in build.sbt add the line:
```scala
libraryDependencies += "au.com.dius.pact.consumer" %% "specs2" % "4.0.1"
```
or if you are using Gradle:
```groovy
dependencies {
testCompile "au.com.dius.pact.consumer:specs2_2.13:4.0.1"
}
```
__*Note:*__ `PactSpec` requires spec2 3.x. Also, for spray users there's an incompatibility between specs2 v3.x and spray.
Follow these instructions to resolve that problem: https://groups.google.com/forum/#!msg/spray-user/2T6SBp4OJeI/AJlnJuAKPRsJ
## Usage
To author a test, mix `PactSpec` into your spec
First we define a service client called `ConsumerService`. In our example this is a simple wrapper for `dispatch`, an HTTP client. The source code can be found in the test folder alongside the `ExamplePactSpec`.
Here is a simple example:
```
import au.com.dius.pact.consumer.PactSpec
class ExamplePactSpec extends Specification with PactSpec {
val consumer = "My Consumer"
val provider = "My Provider"
override def is = uponReceiving("a request for foo")
.matching(path = "/foo")
.willRespondWith(body = "{}")
.withConsumerTest { providerConfig =>
Await.result(ConsumerService(providerConfig.url).simpleGet("/foo"), Duration(1000, MILLISECONDS)) must beEqualTo(200, Some("{}"))
}
}
```
This spec will be run along with the rest of your specs2 unit tests and will output your pact json to
```
/target/pacts/<Consumer>_<Provider>.json
```
# 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`.
# Test Analytics
We are tracking anonymous analytics to gather important usage statistics like JVM version
and operating system. To disable tracking, set the 'pact_do_not_track' system property or environment
variable to 'true'.
Group: au.com.dius.pact.consumer Artifact: specs2_2.13
Show all versions Show documentation Show source
Show all versions Show documentation Show source
0 downloads
Artifact specs2_2.13
Group au.com.dius.pact.consumer
Version 4.2.21
Last update 13. May 2022
Organization not specified
URL https://github.com/DiUS/pact-jvm
License Apache 2
Dependencies amount 5
Dependencies consumer, json, specs2-core_2.13, async-http-client, scala-java8-compat_2.13,
There are maybe transitive dependencies!
Group au.com.dius.pact.consumer
Version 4.2.21
Last update 13. May 2022
Organization not specified
URL https://github.com/DiUS/pact-jvm
License Apache 2
Dependencies amount 5
Dependencies consumer, json, specs2-core_2.13, async-http-client, scala-java8-compat_2.13,
There are maybe transitive dependencies!
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
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!
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
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!
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-server_2.12 from group au.com.dius (version 3.6.15)
Pact server
===========
The pact server is a stand-alone interactions recorder and verifier, aimed at clients that are non-JVM or non-Ruby based.
The pact client for that platform will need to be implemented, but it only be responsible for generating the `JSON`
interactions, running the tests and communicating with the server.
The server implements a `JSON` `REST` Admin API with the following endpoints.
/ -> For diagnostics, currently returns a list of ports of the running mock servers.
/create -> For initialising a test server and submitting the JSON interactions. It returns a port
/complete -> For finalising and verifying the interactions with the server. It writes the `JSON` pact file to disk.
## Running the server
### Versions 2.2.6+
Pact server takes the following parameters:
```
Usage: pact-jvm-server [options] [port]
port
port to run on (defaults to 29999)
--help
prints this usage text
-h <value> | --host <value>
host to bind to (defaults to localhost)
-l <value> | --mock-port-lower <value>
lower bound to allocate mock ports (defaults to 20000)
-u <value> | --mock-port-upper <value>
upper bound to allocate mock ports (defaults to 40000)
-d | --daemon
run as a daemon process
-v <value> | --pact-version <value>
pact version to generate for (2 or 3)
-k <value> | --keystore-path <value>
Path to keystore
-p <value> | --keystore-password <value>
Keystore password
-s <value> | --ssl-port <value>
Ssl port the mock server should run on. lower and upper bounds are ignored
--debug
run with debug logging
```
### Using trust store 3.4.0+
Trust store can be used. However, it is limited to a single port for the time being.
### Prior to version 2.2.6
Pact server takes one optional parameter, the port number to listen on. If not provided, it will listen on 29999.
It requires an active console to run.
### Using a distribution archive
You can download a [distribution from maven central](http://search.maven.org/remotecontent?filepath=au/com/dius/pact-jvm-server_2.11/2.2.4/).
There is both a ZIP and TAR archive. Unpack it to a directory of choice and then run the script in the bin directory.
### Building a distribution bundle
You can build an application bundle with gradle by running (for 2.11 version):
$ ./gradlew :pact-jvm-server_2.11:installdist
This will create an app bundle in `build/2.11/install/pact-jvm-server_2.11`. You can then execute it with:
$ java -jar pact-jvm-server/build/2.10/install/pact-jvm-server_2.11/lib/pact-jvm-server_2.11-3.2.11.jar
or with the generated bundle script file:
$ pact-jvm-server/build/2.11/install/pact-jvm-server_2.11/bin/pact-jvm-server_2.11
By default will run on port `29999` but a port number can be optionally supplied.
### Running it with docker
You can use a docker image to execute the mock server as a docker container.
$ docker run -d -p 8080:8080 -p 20000-20010:20000-20010 uglyog/pact-jvm-server
This will run the main server on port 8080, and each created mock server on ports 20000-20010. You can map the ports to
any you require.
## Life cycle
The following actions are expected to occur
* The client calls `/create` to initialise a server with the expected `JSON` interactions and state
* The admin server will start a mock server on a random port and return the port number in the response
* The client will execute its interaction tests against the mock server with the supplied port
* Once finished, the client will call `/complete' on the Admin API, posting the port number
* The pact server will verify the interactions and write the `JSON` `pact` file to disk under `/target`
* The mock server running on the supplied port will be shutdown.
## Endpoints
### /create
The client will need `POST` to `/create` the generated `JSON` interactions, also providing a state as a query parameter
and a path.
For example:
POST http://localhost:29999/create?state=NoUsers&path=/sub/ref/path '{ "provider": { "name": "Animal_Service"}, ... }'
This will create a new running mock service provider on a randomly generated port. The port will be returned in the
`201` response:
{ "port" : 34423 }
But you can also reference the path from `/sub/ref/path` using the server port. The service will not strip
the prefix path, but instead will use it as a differentiator. If your services do not have differences
in the prefix of their path, then you will have to use the port method.
### /complete
Once the client has finished running its tests against the mock server on the supplied port (in this example port
`34423`) the client will need to `POST` to `/complete` the port number of the mock server that was used.
For example:
POST http://localhost:29999/complete '{ "port" : 34423 }'
This will cause the Pact server to verify the interactions, shutdown the mock server running on that port and writing
the pact `JSON` file to disk under the `target` directory.
### /
The `/` endpoint is for diagnostics and to check that the pact server is running. It will return all the currently
running mock servers port numbers.
For example:
GET http://localhost:29999/
'{ "ports": [23443,43232] }'
2 downloads
Artifact pact-jvm-server_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 4
Dependencies pact-jvm-consumer_2.12, logback-core, logback-classic, scopt_2.12,
There are maybe transitive dependencies!
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 4
Dependencies pact-jvm-consumer_2.12, logback-core, logback-classic, scopt_2.12,
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
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!
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
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!
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
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!
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
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!
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
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!
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!
Page 46 from 3 (items total 482)