Git Product home page Git Product logo

contracttestingboilerplate's Introduction

Contract Testing Boilerplate

Contract Testing Boilerplate has two microservices developed using Spring Boot in a maven multi-module project.

What is Contract Testing?

An integration contract test is a test at the boundary of an external service verifying that it meets the contract expected by a consuming service.

  • Date Provider MicroService - /provider/validDate - Validates whether given date is a valid date or not
  • Age Consumer MicroService - /age-calculate - Returns age of a person based on given date

Microservices

Start Date Provider MicroService by default runs in port 8080:

mvn spring-boot:run -pl date-provider

Start Age Consumer MicroService by default runs in port 8081:

mvn spring-boot:run -pl age-consumer

Pact Tests

Click to expand!

Pact is a contract testing tool. Contract testing is a way to ensure that services (such as an API provider and a client) can communicate with each other. Without contract testing, the only way to know that services can communicate is by using expensive and brittle integration tests.

Run Consumer contract Tests

mvn clean test -pl age-consumer

Generated Pact file:

{
  "provider": {
    "name": "dateProvider"
  },
  "consumer": {
    "name": "ageConsumer"
  },
  "interactions": [
    {
      "description": "valid date from provider",
      "request": {
        "method": "GET",
        "path": "/provider/validDate",
        "query": {
          "date": [
            "2001-02-03"
          ]
        },
        "matchingRules": {
          "query": {
            "date": {
              "matchers": [
                {
                  "match": "date",
                  "date": "2001-02-03"
                }
              ],
              "combine": "AND"
            }
          }
        },
        "generators": {
          "body": {
            "date": {
              "type": "Date",
              "format": "2001-02-03"
            }
          }
        }
      },
      "response": {
        "status": 200,
        "headers": {
          "content-type": "application/json",
          "Content-Type": "application/json; charset=UTF-8"
        },
        "body": {
          "month": 8,
          "year": 2000,
          "isValidDate": true,
          "day": 3
        },
        "matchingRules": {
          "body": {
            "$.year": {
              "matchers": [
                {
                  "match": "number"
                }
              ],
              "combine": "AND"
            },
            "$.month": {
              "matchers": [
                {
                  "match": "number"
                }
              ],
              "combine": "AND"
            },
            "$.day": {
              "matchers": [
                {
                  "match": "number"
                }
              ],
              "combine": "AND"
            },
            "$.isValidDate": {
              "matchers": [
                {
                  "match": "type"
                }
              ],
              "combine": "AND"
            }
          },
          "header": {
            "Content-Type": {
              "matchers": [
                {
                  "match": "regex",
                  "regex": "application/json(;\\s?charset=[\\w\\-]+)?"
                }
              ],
              "combine": "AND"
            }
          }
        }
      },
      "providerStates": [
        {
          "name": ""
        }
      ]
    }
  ],
  "metadata": {
    "pactSpecification": {
      "version": "3.0.0"
    },
    "pact-jvm": {
      "version": "4.0.9"
    }
  }
}

Start Pact Broker at default port :8282

docker-compose up -d

Publish Pact Files in Pact Broker

$ cd age-consumer
$ mvn pact:publish

Verify Pacts in Pact Broker at Provider side

mvn clean -Dtest=PactAgeProviderTest test -pl date-provider

Pact Broker

Spring Cloud Contract Tests

Click to expand!

Spring Cloud Contract is an umbrella project holds solutions to help users implement contract tests. It has two main modules:

  • Spring Cloud Contract Verifier, which is used mainly by the producer side.
  • Spring Cloud Contract Stub Runner, which is used by the consumer side.

Blogs

contracttestingboilerplate's People

Contributors

dependabot-preview[bot] avatar dependabot[bot] avatar df-wu avatar saikrishna321 avatar srinivasantarget avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

contracttestingboilerplate's Issues

DateProducerTest.java file needs to be updated

As it currently stands running this code leads to the following error:

"C:\Program Files\Java\jdk1.8.0_251\bin\java.exe" -ea -Didea.test.cyclic.buffer.size=1048576 "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2020.2.2\lib\idea_rt.jar=53615:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2020.2.2\bin" -Dfile.encoding=UTF-8 -classpath "C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2020.2.2\lib\idea_rt.jar" com.intellij.rt.execution.CommandLineWrapper C:\Users\anchit\AppData\Local\Temp\idea_classpath700658868 com.intellij.rt.junit.JUnitStarter -ideVersion5 -junit4 pactContract.provisioning.PactProviderTest
12:46:12.130 [main] DEBUG au.com.dius.pact.provider.junit.PactRunner - Found annotation @au.com.dius.pact.provider.junitsupport.Provider(value=providerSiteProvisioning)
12:46:12.139 [main] DEBUG au.com.dius.pact.provider.junit.PactRunner - Found annotation @au.com.dius.pact.provider.junitsupport.Consumer(value=consumerSearchIndexer)
12:46:13.311 [main] DEBUG au.com.dius.pact.provider.ProviderUtils - Pact source does not have a constructor with one argument of type Class
org.junit.runners.model.InitializationError
	at au.com.dius.pact.provider.junit.InteractionRunner.validate(InteractionRunner.kt:98)
	at au.com.dius.pact.provider.junit.InteractionRunner.<init>(InteractionRunner.kt:67)
	at au.com.dius.pact.provider.junit.PactRunner.newInteractionRunner(PactRunner.kt:143)
	at au.com.dius.pact.provider.junit.PactRunner.setupInteractionRunners(PactRunner.kt:134)
	at au.com.dius.pact.provider.junit.PactRunner.initialize(PactRunner.kt:127)
	at au.com.dius.pact.provider.junit.PactRunner.getChildren(PactRunner.kt:151)
	at org.junit.runners.ParentRunner.getFilteredChildren(ParentRunner.java:426)
	at org.junit.runners.ParentRunner.getDescription(ParentRunner.java:351)
	at com.intellij.junit4.JUnit4IdeaTestRunner.getDescription(JUnit4IdeaTestRunner.java:79)
	at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:51)
	at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
	at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:220)
	at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:53)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at com.intellij.rt.execution.CommandLineWrapper.main(CommandLineWrapper.java:63)

Process finished with exit code -2

This can be fixed by updating the test target in the DateProducerTest.java file to the following:

@testtarget
public final Target target = new MessageTarget();

DateConsumerTest.java needs to be updated

The consumer test code as it is currently doesn't fetch the message. Instead, we need to modify it with the following:

  • Add @PactVerification({"provider name"}) annotation to the @test method
  • Remove the args to the test method
  • Create one more method with the following code:

public void setMessage(byte[] messageContents) {
System.out.println("Did the call come to setMessage?");
//Set the class member currentMessage value as the arg received from this function
currentMessage = messageContents;
}

This function gets called automatically by Pact during execution and it fetches the message.

  • Modify the @test method where all verifications are performed on the stored class variable (which will be set by Pact via setMessage)

For example, the test can have the following code:

Assert.assertNotNull(new String(currentMessage));

Whitelabel Error Page

Hi, I have started both date provider and age consumer microservices using the mvn commands. When I go to localhost:8080 and 8081, I get this error :
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Tue Sep 20 19:10:22 BST 2022
There was an unexpected error (type=Not Found, status=404).

How do I fix this?. Thank you.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.