concept contract in category java

appears as: contract, contracts, contracts, contract, The contract
Testing Java Microservices: Using Arquillian, Hoverfly, AssertJ, JUnit, Selenium, and Mockito

This is an excerpt from Manning's book Testing Java Microservices: Using Arquillian, Hoverfly, AssertJ, JUnit, Selenium, and Mockito.

A BOM is used to define the versions and transient dependencies of specific artifacts that are likely to be used in the project. In a multimodule build, <dependencyManagement> should be in the parent pom.xml and serve as a contract for all the child modules. The actual dependencies used are then defined in the <dependencies> section, where the <version> definition is omitted.

As mentioned, a contract is a list of agreements between a service that acts as a client (or consumer) and another service that acts as a provider. The existence of a contract defining interactions between each consumer and its provider fixes all the problems described in section 6.1.3.

In figure 6.6, a contract between consumers and a provider is defined—let’s say, by having a file describe it—and thus both provider and consumers have an agreement to follow. Now the relationship between consumers and the provider is indirect, because from the producer’s point of view, you only need to verify that it meets the agreement described in the contract. The provider doesn’t need to run the consumer’s integration tests; it only needs to test that the consumer is able to consume requests and produce responses following the contract.

If the ownership of the contract lies with the team that’s developing the provider, this implies that they not only know the business behavior of their own service (the provider) but also the requirements of all consumers their service supports. This kind of contract is called a provider contract because the contract belongs to the provider, and consumers are merely viewers of it (see figure 6.7). One example of where such a contract might be beneficial is an internal security authentication/authorization service, where consuming services must conform to the provider contract.

Figure 6.7. Provider contracts

Provider contracts define what the provider will offer to consumers. Each consumer must adapt to what the provider offers. Naturally, this implies that the consumer is coupled to the provider. If the contract developed by the provider team no longer satisfies the requirements of a consumer, the consumer team must start a conversation with the maintainers of the provider service to address this deficiency.

This test uses Arquillian standalone, because there’s no @Deployment method. At this point, you don’t need to deploy anything to the container. The contract for sending a comment to the comments service is defined in putCommentFragment, which defines the contract with the expected body and the canned response. Finally, there are the assertions for validating that the CommentsGateway class works as expected.

Now let’s write the contract for getting comments for a given gameId (code/aggregator/c-tests/src/test/javahttps://livebook.manning.com/book/aggr/CommentsContractTest.java). In this case, you need to set a state for telling the provider which data you expect to be returned when the contract is validated against it.

Listing 6.9. Getting comments for a game
@StubServer
URL url;

public PactFragment getCommentsFragment(PactDslWithProvider
                                                builder) {

    final Map<String, String> headers = new HashMap<>();
    headers.put("Content-Type", "application/json");

    return builder.given("A game with id 12 with rate 5 and " +
            "message This Game is Awesome")                          #1
            .uponReceiving("User gets comments for given Game")
            .matchPath("/comments/12").method("GET")
            .willRespondWith().status(200).headers(headers)
            .body(toJson(commentResult)).toFragment();

}

@Test
@PactVerification(fragment = "getCommentsFragment")
public void shouldGetComentsFromCommentsService() throws
        ExecutionException, InterruptedException {
    final CommentsGateway commentsGateway = new CommentsGateway();
    commentsGateway.initRestClient(url.toString());

    final Future<JsonObject> comments = commentsGateway
            .getCommentsFromCommentsService(12);
    final JsonObject commentsResponse = comments.get();

    assertThat(commentsResponse.getJsonNumber("rate")
            .doubleValue()).isEqualTo(5);                           #2
    assertThat(commentsResponse.getInt("total")).isEqualTo(1);
    assertThat(commentsResponse.getJsonArray("comments"))
            .hasSize(1);

}

Notice that the definition of the contract is similar to the previous one. The biggest difference is the use of the given method to set a state. In this case, you’re setting the data that will be required on the provider side.

Finally, you need to configure Arquillian Algeron to publish contracts in a shared place, so the provider can retrieve and validate them (code/aggregator/c-tests/src/test/resources/arquillian.xml). For the sake of simplicity, the folder approach is used here, but in the real world you’d probably use a Git repository.

Listing 6.10. Publishing contracts in a shared location
<?xml version="1.0"?>
<arquillian
xsi:schemaLocation="http://jboss.org/schema/arquillian
http://jboss.org/schema/arquillian/arquillian_1_0.xsd"
xmlns="http://jboss.org/schema/arquillian"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <extension qualifier="algeron-consumer">
        <property name="publishConfiguration"> provider: folder
          outputFolder: /tmp/mypacts
          contractsFolder: target/pacts
        </property>
        <property name="publishContracts">
          ${env.publishcontracts:true}
        </property>
    </extension>
</arquillian>

Now that you’ve written the contract for the consumer side, let’s see what you need to do to validate it against the provider.

Pact JVM is partially written in Scala, Groovy, and Java, but it can be used with any JVM language. It integrates perfectly with Java, Scala, Groovy, Grails (providing a Groovy DSL for defining contracts), and Clojure. In addition, it offers tight integration with test frameworks like JUnit, Spock, ScalaTest, and Specs2, as well as build tools such as Maven, Gradle, Leiningen, and sbt. This book focuses on Java tools, but keep in mind that if you plan to use any other JVM language, you can still use Pact JVM for consumer-driven contract testing.