JUnit

Component Runtime :: Testing :: HTTP

org.talend.sdk.component : component-runtime-http-junit

JUnit integration to simplify the HTTP API testing/mocking.

Last Version: 1.46.0

Release Date:

Last Version: 1.46.0

Release Date:

TeaVM JUnit runner

org.teavm : teavm-junit

TeaVM implementation of JUnit API

Last Version: 0.7.0

Release Date:

Last Version: 2.8.1

Release Date:

Last Version: 2.0.7

Release Date:

Guice Integration Test

org.testifyproject.junit4 : guice-integration-test

A module that contains a JUnit test runner for running Guice integration tests

Last Version: 1.0.6

Release Date:

Unit Test

org.testifyproject.junit4 : unit-test

A meta module that points to junit4-core module which contains a JUnit test runner for running unit tests

Last Version: 1.0.6

Release Date:

webtau-junit5

org.testingisdocumenting.webtau : webtau-junit5

WebTau - web test automation. REST/GraphQL/DB/CLI/UI testing framework.

Last Version: 1.48

Release Date:

webtau-junit5-groovy

org.testingisdocumenting.webtau : webtau-junit5-groovy

WebTau - web test automation. REST/GraphQL/DB/CLI/UI testing framework.

Last Version: 1.48

Release Date:

Last Version: 6.3.2.1

Release Date:

Last Version: 1.0.0

Release Date:

Last Version: 5.0.1

Release Date:

Last Version: 5.0.1

Release Date:

Last Version: 1.0.0

Release Date:

junit

io.avaje : junit

Parent for avaje java8 open source projects.

Last Version: 1.1

Release Date:

JGit - JUnit Ssh Utility Classes

org.openl.jgit : org.eclipse.jgit.junit.ssh

Utility classes to support Ssh based JUnit testing of JGit applications.

Last Version: 6.1.0.202205052100-r

Release Date:

pact-jvm-consumer-junit_2.11

au.com.dius : pact-jvm-consumer-junit_2.11

pact-jvm-consumer-junit ======================= Provides a DSL and a base test class for use with Junit to build consumer tests. ## Dependency The library is available on maven central using: * group-id = `au.com.dius` * artifact-id = `pact-jvm-consumer-junit_2.12` * version-id = `3.5.x` ## Usage ### Using the base ConsumerPactTest To write a pact spec extend ConsumerPactTestMk2. This base class defines the following four methods which must be overridden in your test class. * *providerName:* Returns the name of the API provider that Pact will mock * *consumerName:* Returns the name of the API consumer that we are testing. * *createFragment:* Returns the PactFragment containing the interactions that the test setup using the ConsumerPactBuilder DSL * *runTest:* The actual test run. It receives the URL to the mock server as a parameter. Here is an example: ```java import au.com.dius.pact.consumer.dsl.PactDslWithProvider; import au.com.dius.pact.consumer.exampleclients.ConsumerClient; import au.com.dius.pact.consumer.ConsumerPactTest; import au.com.dius.pact.model.PactFragment; import org.junit.Assert; import java.io.IOException; import java.util.HashMap; import java.util.Map; import static org.junit.Assert.assertEquals; public class ExampleJavaConsumerPactTest extends ConsumerPactTestMk2 { @Override protected RequestResponsePact createFragment(PactDslWithProvider builder) { Map<String, String> headers = new HashMap<String, String>(); headers.put("testreqheader", "testreqheadervalue"); return builder .given("test state") // NOTE: Using provider states are optional, you can leave it out .uponReceiving("ExampleJavaConsumerPactTest test interaction") .path("/") .method("GET") .headers(headers) .willRespondWith() .status(200) .headers(headers) .body("{\"responsetest\": true, \"name\": \"harry\"}") .given("test state 2") // NOTE: Using provider states are optional, you can leave it out .uponReceiving("ExampleJavaConsumerPactTest second test interaction") .method("OPTIONS") .headers(headers) .path("/second") .body("") .willRespondWith() .status(200) .headers(headers) .body("") .toPact(); } @Override protected String providerName() { return "test_provider"; } @Override protected String consumerName() { return "test_consumer"; } @Override protected void runTest(MockServer mockServer) throws IOException { Assert.assertEquals(new ConsumerClient(mockServer.getUrl()).options("/second"), 200); Map expectedResponse = new HashMap(); expectedResponse.put("responsetest", true); expectedResponse.put("name", "harry"); assertEquals(new ConsumerClient(mockServer.getUrl()).getAsMap("/", ""), expectedResponse); assertEquals(new ConsumerClient(mockServer.getUrl()).options("/second"), 200); } } ``` ### Using the Pact JUnit Rule Thanks to [@warmuuh](https://github.com/warmuuh) we have a JUnit rule that simplifies running Pact consumer tests. To use it, create a test class and then add the rule: #### 1. Add the Pact Rule to your test class to represent your provider. ```java @Rule public PactProviderRuleMk2 mockProvider = new PactProviderRuleMk2("test_provider", "localhost", 8080, this); ``` The hostname and port are optional. If left out, it will default to 127.0.0.1 and a random available port. You can get the URL and port from the pact provider rule. #### 2. Annotate a method with Pact that returns a pact fragment for the provider and consumer ```java @Pact(provider="test_provider", consumer="test_consumer") public RequestResponsePact createPact(PactDslWithProvider builder) { return builder .given("test state") .uponReceiving("ExampleJavaConsumerPactRuleTest test interaction") .path("/") .method("GET") .willRespondWith() .status(200) .body("{\"responsetest\": true}") .toPact(); } ``` ##### Versions 3.0.2/2.2.13+ You can leave the provider name out. It will then use the provider name of the first mock provider found. I.e., ```java @Pact(consumer="test_consumer") // will default to the provider name from mockProvider public RequestResponsePact createFragment(PactDslWithProvider builder) { return builder .given("test state") .uponReceiving("ExampleJavaConsumerPactRuleTest test interaction") .path("/") .method("GET") .willRespondWith() .status(200) .body("{\"responsetest\": true}") .toPact(); } ``` #### 3. Annotate your test method with PactVerification to have it run in the context of the mock server setup with the appropriate pact from step 1 and 2 ```java @Test @PactVerification("test_provider") public void runTest() { Map expectedResponse = new HashMap(); expectedResponse.put("responsetest", true); assertEquals(new ConsumerClient(mockProvider.getUrl()).get("/"), expectedResponse); } ``` ##### Versions 3.0.2/2.2.13+ You can leave the provider name out. It will then use the provider name of the first mock provider found. I.e., ```java @Test @PactVerification public void runTest() { // This will run against mockProvider Map expectedResponse = new HashMap(); expectedResponse.put("responsetest", true); assertEquals(new ConsumerClient("http://localhost:8080").get("/"), expectedResponse); } ``` For an example, have a look at [ExampleJavaConsumerPactRuleTest](src/test/java/au/com/dius/pact/consumer/examples/ExampleJavaConsumerPactRuleTest.java) ### Requiring a test with multiple providers The Pact Rule can be used to test with multiple providers. Just add a rule to the test class for each provider, and then include all the providers required in the `@PactVerification` annotation. For an example, look at [PactMultiProviderTest](src/test/java/au/com/dius/pact/consumer/pactproviderrule/PactMultiProviderTest.java). Note that if more than one provider fails verification for the same test, you will only receive a failure for one of them. Also, to have multiple tests in the same test class, the providers must be setup with random ports (i.e. don't specify a hostname and port). Also, if the provider name is left out of any of the annotations, the first one found will be used (which may not be the first one defined). ### Requiring the mock server to run with HTTPS [versions 3.2.7/2.4.9+] From versions 3.2.7/2.4.9+ the mock server can be started running with HTTPS using a self-signed certificate instead of HTTP. To enable this set the `https` parameter to `true`. E.g.: ```java @Rule public PactProviderRule mockTestProvider = new PactProviderRule("test_provider", "localhost", 8443, true, PactSpecVersion.V2, this); // ^^^^ ``` For an example test doing this, see [PactProviderHttpsTest](src/test/java/au/com/dius/pact/consumer/pactproviderrule/PactProviderHttpsTest.java). **NOTE:** The provider will start handling HTTPS requests using a self-signed certificate. Most HTTP clients will not accept connections to a self-signed server as the certificate is untrusted. You may need to enable insecure HTTPS with your client for this test to work. For an example of how to enable insecure HTTPS client connections with Apache Http Client, have a look at [InsecureHttpsRequest](src/test/java/org/apache/http/client/fluent/InsecureHttpsRequest.java). ### Requiring the mock server to run with HTTPS with a keystore [versions 3.4.1+] From versions 3.4.1+ the mock server can be started running with HTTPS using a keystore. To enable this set the `https` parameter to `true`, set the keystore path/file, and the keystore's password. E.g.: ```java @Rule public PactProviderRule mockTestProvider = new PactProviderRule("test_provider", "localhost", 8443, true, "/path/to/your/keystore.jks", "your-keystore-password", PactSpecVersion.V2, this); ``` For an example test doing this, see [PactProviderHttpsKeystoreTest](src/test/java/au/com/dius/pact/consumer/pactproviderrule/PactProviderHttpsKeystoreTest.java). ### Setting default expected request and response values [versions 3.5.10+] If you have a lot of tests that may share some values (like headers), you can setup default values that will be applied to all the expected requests and responses for the tests. To do this, you need to create a method that takes single parameter of the appropriate type (`PactDslRequestWithoutPath` or `PactDslResponse`) and annotate it with the default marker annotation (`@DefaultRequestValues` or `@DefaultResponseValues`). For example: ```java @DefaultRequestValues public void defaultRequestValues(PactDslRequestWithoutPath request) { Map<String, String> headers = new HashMap<String, String>(); headers.put("testreqheader", "testreqheadervalue"); request.headers(headers); } @DefaultResponseValues public void defaultResponseValues(PactDslResponse response) { Map<String, String> headers = new HashMap<String, String>(); headers.put("testresheader", "testresheadervalue"); response.headers(headers); } ``` For an example test that uses these, have a look at [PactProviderWithMultipleFragmentsTest](src/test/java/au/com/dius/pact/consumer/pactproviderrule/PactProviderWithMultipleFragmentsTest.java) ### Note on HTTP clients and persistent connections Some HTTP clients may keep the connection open, based on the live connections settings or if they use a connection cache. This could cause your tests to fail if the client you are testing lives longer than an individual test, as the mock server will be started and shutdown for each test. This will result in the HTTP client connection cache having invalid connections. For an example of this where the there was a failure for every second test, see [Issue #342](https://github.com/DiUS/pact-jvm/issues/342). ### Using the Pact DSL directly Sometimes it is not convenient to use the ConsumerPactTest as it only allows one test per test class. The DSL can be used directly in this case. Example: ```java import au.com.dius.pact.consumer.ConsumerPactBuilder; import au.com.dius.pact.consumer.PactVerificationResult; import au.com.dius.pact.consumer.exampleclients.ProviderClient; import au.com.dius.pact.model.MockProviderConfig; import au.com.dius.pact.model.RequestResponsePact; import org.junit.Test; import java.io.IOException; import java.util.HashMap; import java.util.Map; import static au.com.dius.pact.consumer.ConsumerPactRunnerKt.runConsumerTest; import static org.junit.Assert.assertEquals; /** * Sometimes it is not convenient to use the ConsumerPactTest as it only allows one test per test class. * The DSL can be used directly in this case. */ public class DirectDSLConsumerPactTest { @Test public void testPact() { RequestResponsePact pact = ConsumerPactBuilder .consumer("Some Consumer") .hasPactWith("Some Provider") .uponReceiving("a request to say Hello") .path("/hello") .method("POST") .body("{\"name\": \"harry\"}") .willRespondWith() .status(200) .body("{\"hello\": \"harry\"}") .toPact(); MockProviderConfig config = MockProviderConfig.createDefault(); PactVerificationResult result = runConsumerTest(pact, config, mockServer -> { Map expectedResponse = new HashMap(); expectedResponse.put("hello", "harry"); try { assertEquals(new ProviderClient(mockServer.getUrl()).hello("{\"name\": \"harry\"}"), expectedResponse); } catch (IOException e) { throw new RuntimeException(e); } }); if (result instanceof PactVerificationResult.Error) { throw new RuntimeException(((PactVerificationResult.Error)result).getError()); } assertEquals(PactVerificationResult.Ok.INSTANCE, result); } } ``` ### The Pact JUnit DSL The DSL has the following pattern: ```java .consumer("Some Consumer") .hasPactWith("Some Provider") .given("a certain state on the provider") .uponReceiving("a request for something") .path("/hello") .method("POST") .body("{\"name\": \"harry\"}") .willRespondWith() .status(200) .body("{\"hello\": \"harry\"}") .uponReceiving("another request for something") .path("/hello") .method("POST") .body("{\"name\": \"harry\"}") .willRespondWith() .status(200) .body("{\"hello\": \"harry\"}") . . . .toPact() ``` You can define as many interactions as required. Each interaction starts with `uponReceiving` followed by `willRespondWith`. The test state setup with `given` is a mechanism to describe what the state of the provider should be in before the provider is verified. It is only recorded in the consumer tests and used by the provider verification tasks. ### Building JSON bodies with PactDslJsonBody DSL **NOTE:** If you are using Java 8, there is [an updated DSL for consumer tests](../pact-jvm-consumer-java8). The body method of the ConsumerPactBuilder can accept a PactDslJsonBody, which can construct a JSON body as well as define regex and type matchers. For example: ```java PactDslJsonBody body = new PactDslJsonBody() .stringType("name") .booleanType("happy") .hexValue("hexCode") .id() .ipAddress("localAddress") .numberValue("age", 100) .timestamp(); ``` #### DSL Matching methods The following matching methods are provided with the DSL. In most cases, they take an optional value parameter which will be used to generate example values (i.e. when returning a mock response). If no example value is given, a random one will be generated. | method | description | |--------|-------------| | string, stringValue | Match a string value (using string equality) | | number, numberValue | Match a number value (using Number.equals)\* | | booleanValue | Match a boolean value (using equality) | | stringType | Will match all Strings | | numberType | Will match all numbers\* | | integerType | Will match all numbers that are integers (both ints and longs)\* | | decimalType | Will match all real numbers (floating point and decimal)\* | | booleanType | Will match all boolean values (true and false) | | stringMatcher | Will match strings using the provided regular expression | | timestamp | Will match string containing timestamps. If a timestamp format is not given, will match an ISO timestamp format | | date | Will match string containing dates. If a date format is not given, will match an ISO date format | | time | Will match string containing times. If a time format is not given, will match an ISO time format | | ipAddress | Will match string containing IP4 formatted address. | | id | Will match all numbers by type | | hexValue | Will match all hexadecimal encoded strings | | uuid | Will match strings containing UUIDs | | includesStr | Will match strings containing the provided string | | equalsTo | Will match using equals | | matchUrl | Defines a matcher for URLs, given the base URL path and a sequence of path fragments. The path fragments could be strings or regular expression matchers | _\* Note:_ JSON only supports double precision floating point values. Depending on the language implementation, they may parsed as integer, floating point or decimal numbers. #### Ensuring all items in a list match an example (2.2.0+) Lots of the time you might not know the number of items that will be in a list, but you want to ensure that the list has a minimum or maximum size and that each item in the list matches a given example. You can do this with the `arrayLike`, `minArrayLike` and `maxArrayLike` functions. | function | description | |----------|-------------| | `eachLike` | Ensure that each item in the list matches the provided example | | `maxArrayLike` | Ensure that each item in the list matches the provided example and the list is no bigger than the provided max | | `minArrayLike` | Ensure that each item in the list matches the provided example and the list is no smaller than the provided min | For example: ```java DslPart body = new PactDslJsonBody() .minArrayLike("users", 1) .id() .stringType("name") .closeObject() .closeArray(); ``` This will ensure that the users list is never empty and that each user has an identifier that is a number and a name that is a string. __Version 3.2.4/2.4.6+__ You can specify the number of example items to generate in the array. The default is 1. ```java DslPart body = new PactDslJsonBody() .minArrayLike("users", 1, 2) .id() .stringType("name") .closeObject() .closeArray(); ``` This will generate the example body with 2 items in the users list. #### Root level arrays that match all items (version 2.2.11+) If the root of the body is an array, you can create PactDslJsonArray classes with the following methods: | function | description | |----------|-------------| | `arrayEachLike` | Ensure that each item in the list matches the provided example | | `arrayMinLike` | Ensure that each item in the list matches the provided example and the list is no bigger than the provided max | | `arrayMaxLike` | Ensure that each item in the list matches the provided example and the list is no smaller than the provided min | For example: ```java PactDslJsonArray.arrayEachLike() .date("clearedDate", "mm/dd/yyyy", date) .stringType("status", "STATUS") .decimalType("amount", 100.0) .closeObject() ``` This will then match a body like: ```json [ { "clearedDate" : "07/22/2015", "status" : "C", "amount" : 15.0 }, { "clearedDate" : "07/22/2015", "status" : "C", "amount" : 15.0 }, { "clearedDate" : "07/22/2015", "status" : "C", "amount" : 15.0 } ] ``` __Version 3.2.4/2.4.6+__ You can specify the number of example items to generate in the array. The default is 1. #### Matching JSON values at the root (Version 3.2.2/2.4.3+) For cases where you are expecting basic JSON values (strings, numbers, booleans and null) at the root level of the body and need to use matchers, you can use the `PactDslJsonRootValue` class. It has all the DSL matching methods for basic values that you can use. For example: ```java .consumer("Some Consumer") .hasPactWith("Some Provider") .uponReceiving("a request for a basic JSON value") .path("/hello") .willRespondWith() .status(200) .body(PactDslJsonRootValue.integerType()) ``` #### Matching any key in a map (3.3.1/2.5.0+) The DSL has been extended for cases where the keys in a map are IDs. For an example of this, see [#313](https://github.com/DiUS/pact-jvm/issues/313). In this case you can use the `eachKeyLike` method, which takes an example key as a parameter. For example: ```java DslPart body = new PactDslJsonBody() .object("one") .eachKeyLike("001", PactDslJsonRootValue.id(12345L)) // key like an id mapped to a matcher .closeObject() .object("two") .eachKeyLike("001-A") // key like an id where the value is matched by the following example .stringType("description", "Some Description") .closeObject() .closeObject() .object("three") .eachKeyMappedToAnArrayLike("001") // key like an id mapped to an array where each item is matched by the following example .id("someId", 23456L) .closeObject() .closeArray() .closeObject(); ``` For an example, have a look at [WildcardKeysTest](src/test/java/au/com/dius/pact/consumer/WildcardKeysTest.java). **NOTE:** The `eachKeyLike` method adds a `*` to the matching path, so the matching definition will be applied to all keys of the map if there is not a more specific matcher defined for a particular key. Having more than one `eachKeyLike` condition applied to a map will result in only one being applied when the pact is verified (probably the last). **Further Note: From version 3.5.22 onwards pacts with wildcards applied to map keys will require the Java system property "pact.matching.wildcard" set to value "true" when the pact file is verified.** #### Combining matching rules with AND/OR Matching rules can be combined with AND/OR. There are two methods available on the DSL for this. For example: ```java DslPart body = new PactDslJsonBody() .numberValue("valueA", 100) .and("valueB","AB", PM.includesStr("A"), PM.includesStr("B")) // Must match both matching rules .or("valueC", null, PM.date(), PM.nullValue()) // will match either a valid date or a null value ``` The `and` and `or` methods take a variable number of matchers (varargs). ### Matching on paths (version 2.1.5+) You can use regular expressions to match incoming requests. The DSL has a `matchPath` method for this. You can provide a real path as a second value to use when generating requests, and if you leave it out it will generate a random one from the regular expression. For example: ```java .given("test state") .uponReceiving("a test interaction") .matchPath("/transaction/[0-9]+") // or .matchPath("/transaction/[0-9]+", "/transaction/1234567890") .method("POST") .body("{\"name\": \"harry\"}") .willRespondWith() .status(200) .body("{\"hello\": \"harry\"}") ``` ### Matching on headers (version 2.2.2+) You can use regular expressions to match request and response headers. The DSL has a `matchHeader` method for this. You can provide an example header value to use when generating requests and responses, and if you leave it out it will generate a random one from the regular expression. For example: ```java .given("test state") .uponReceiving("a test interaction") .path("/hello") .method("POST") .matchHeader("testreqheader", "test.*value") .body("{\"name\": \"harry\"}") .willRespondWith() .status(200) .body("{\"hello\": \"harry\"}") .matchHeader("Location", ".*/hello/[0-9]+", "/hello/1234") ``` ### Matching on query parameters (version 3.3.7+) You can use regular expressions to match request query parameters. The DSL has a `matchQuery` method for this. You can provide an example value to use when generating requests, and if you leave it out it will generate a random one from the regular expression. For example: ```java .given("test state") .uponReceiving("a test interaction") .path("/hello") .method("POST") .matchQuery("a", "\\d+", "100") .matchQuery("b", "[A-Z]", "X") .body("{\"name\": \"harry\"}") .willRespondWith() .status(200) .body("{\"hello\": \"harry\"}") ``` ## Debugging pact failures When the test runs, Pact will start a mock provider that will listen for requests and match them against the expectations you setup in `createFragment`. If the request does not match, it will return a 500 error response. Each request received and the generated response is logged using [SLF4J](http://www.slf4j.org/). Just enable debug level logging for au.com.dius.pact.consumer.UnfilteredMockProvider. Most failures tend to be mismatched headers or bodies. ## Changing the directory pact files are written to (2.1.9+) By default, pact files are written to `target/pacts`, 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/pacts" } ``` 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.basedir}/target</buildDirectory> [...] </systemPropertyVariables> </configuration> </plugin> </plugins> </build> [...] </project> ``` For SBT: ```scala fork in Test := true, javaOptions in Test := Seq("-Dpact.rootDir=some/other/directory") ``` # Publishing your pact files to a pact broker If you use Gradle, you can use the [pact Gradle plugin](https://github.com/DiUS/pact-jvm/tree/master/pact-jvm-provider-gradle#publishing-pact-files-to-a-pact-broker) to publish your pact files. # Pact Specification V3 Version 3 of the pact specification changes the format of pact files in the following ways: * Query parameters are stored in a map form and are un-encoded (see [#66](https://github.com/DiUS/pact-jvm/issues/66) and [#97](https://github.com/DiUS/pact-jvm/issues/97) for information on what this can cause). * Introduces a new message pact format for testing interactions via a message queue. * Multiple provider states can be defined with data parameters. ## Generating V2 spec pact files (3.1.0+, 2.3.0+) To have your consumer tests generate V2 format pacts, you can set the specification version to V2. If you're using the `ConsumerPactTest` base class, you can override the `getSpecificationVersion` method. For example: ```java @Override protected PactSpecVersion getSpecificationVersion() { return PactSpecVersion.V2; } ``` If you are using the `PactProviderRuleMk2`, you can pass the version into the constructor for the rule. ```java @Rule public PactProviderRuleMk2 mockTestProvider = new PactProviderRuleMk2("test_provider", PactSpecVersion.V2, this); ``` ## Consumer test for a message consumer For testing a consumer of messages from a message queue, the `MessagePactProviderRule` rule class works in much the same way as the `PactProviderRule` class for Request-Response interactions, but will generate a V3 format message pact file. For an example, look at [ExampleMessageConsumerTest](https://github.com/DiUS/pact-jvm/blob/master/pact-jvm-consumer-junit%2Fsrc%2Ftest%2Fjava%2Fau%2Fcom%2Fdius%2Fpact%2Fconsumer%2Fv3%2FExampleMessageConsumerTest.java)

Last Version: 3.5.24

Release Date:

pact-jvm-provider-junit_2.11

au.com.dius : pact-jvm-provider-junit_2.11

# 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+].

Last Version: 3.5.24

Release Date:

biz.aQute.tester.junit-platform

biz.aQute.bnd : biz.aQute.tester.junit-platform

A bnd tester using JUnit Platform. Like biz.aQute.tester, this bundle will add itself to the -runbundles at the end. At startup, this bundle will then look for TestEngine implementations among the loaded bundles and use them to execute the tests. This bundle does NOT contain the necessary TestEngine implementations for JUnit 3, 4 or 5 - it will import them just like any other bundle.

Last Version: 6.3.1

Release Date:

Last Version: 5.6.0-1

Release Date:

JEAF JUnit Extensions Impl

com.anaptecs.jeaf.junit : jeaf-junit-extensions

Project provides a JUnit extensions so that JEAF Services can be run in JUnit environments without having the need to start a web or application server.

Last Version: 1.6.13

Release Date:

Last Version: 3.1.0

Release Date:

Last Version: 1.1

Release Date:

Bobcat JUnit 5

com.cognifide.qa.bb : bb-junit5

Bobcat is an automated testing framework for functional testing of web applications.

Last Version: 2.3.0

Release Date:

Last Version: 5.1.1

Release Date:

Last Version: 1.3.2

Release Date:

Last Version: 1.0

Release Date:

Last Version: 0.2

Release Date:

JUnit4 for OSGi Registry

com.github.nfalco79 : junit4osgi-registry

This bundle registers different test registry as OSGi service.

Last Version: 1.2.15

Release Date:

Last Version: 0.0.1

Release Date:

Last Version: 1.1

Release Date:

Last Version: 1.1

Release Date:

Last Version: 1.0.0

Release Date:

Last Version: 1.0.1

Release Date:

Armeria (armeria-junit5)

com.linecorp.armeria : armeria-junit5

Asynchronous HTTP/2 RPC/REST client/server library built on top of Java 8, Netty, Thrift and gRPC (armeria-junit5)

Last Version: 1.16.0

Release Date:

kafka-junit4

com.salesforce.kafka.test : kafka-junit4

This library wraps Kafka's embedded test cluster, allowing you to more easily create and run integration tests using JUnit against a "real" kafka server running within the context of your tests.

Last Version: 3.2.4

Release Date:

JUnitRecorder Core

com.seitenbau.testing : sb-junitrecorder-core

Write a few paragraphs to say what your project is about.

Last Version: 1.0.0

Release Date:

ArchUnit

com.tngtech.archunit : archunit-junit5-engine-api

A Java architecture test library, to specify and assert architecture rules in plain Java - Module 'archunit-junit5-engine-api'

Last Version: 0.23.1

Release Date:

jgiven-spring-junit4

com.tngtech.jgiven : jgiven-spring-junit4

Module for using Spring dependency injection together with JGiven and JUnit 4

Last Version: 1.2.2

Release Date:

Last Version: 0.5

Release Date:

cdi-test api

de.hilling.junit.cdi : cdi-test-api

Basic annotations and interfaces for cdi-test

Last Version: 4.0.0-RC6

Release Date:

quantummaid-junit5

de.quantummaid.quantummaid.integrations : quantummaid-junit5

This parent pom is supposed to be used as a parent for all QuantumMaid open source projects to reliably enable the enforcement of java standards like library blacklisting, code style rules, and more.

Last Version: 1.1.1

Release Date:

de.rwth.swc.coffee4j:coffee4j-junit-jupiter

de.rwth.swc.coffee4j : coffee4j-junit-jupiter

coffee4j is a framework that integrates combinatorial test generation and automated test execution via JUnit5

Last Version: 1.0.6

Release Date:

Last Version: 1.0.0-M5

Release Date:

Last Version: 1.0.0-M10

Release Date:

SII test plugin :: JUnit

fr.sii.sonar : sonar-test-junit

Plugin that parses JUnit xml report

Last Version: 2.1.0

Release Date:

roaster-tm4j-junit5

hu.icellmobilsoft.roaster : roaster-tm4j-junit5

Developer and Intergration test framework based on coff:ee

Last Version: 0.7.0

Release Date:

schemaregistry-junit

io.github.data-rocks-team : schemaregistry-junit-core

A library that provides an in-memory instance of Confluent Schema Registry to run your tests against.

Last Version: 0.1.1

Release Date:

Last Version: 5.3.2

Release Date:

Last Version: 0.5.2

Release Date: