EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login
Home Software Development Software Development Tutorials Spring Tutorial Spring Cloud Contract
Secondary Sidebar
Spring Tutorial
  • Spring Cloud Basics
    • What is Spring Cloud
    • Spring Cloud Contract
    • Spring Cloud Components
    • Spring Cloud Version
    • Spring Cloud Data Flow
    • Spring cloud stream
    • Spring Cloud Dependencies
    • Spring cloud microservices
    • spring cloud gateway
    • Spring Cloud Config
    • Spring Cloud Kubernetes
    • Spring Cloud Sleuth
  • Spring
    • What is Spring Framework?
    • Spring Architecture
    • What is Spring Integration?
    • IoC Containers
    • What is AOP?
    • Spring Modules
    • Spring Batch Processing
    • Spring Batch Partitioner
    • Spring Batch Job
    • Spring AOP
    • Spring Expression Language
    • Dependency Injection in Spring
    • Spring Batch Architecture
    • Spring framework Interview Questions
  • Spring Boot
    • What is Spring Boot
    • Spring Boot flyway
    • Spring Boot framework
    • Spring Boot Logback
    • Spring Boot actuator endpoints
    • Spring Boot gRPC
    • Spring Boot jdbctemplate example
    • Spring Boot ehcache
    • Spring Boot Architecture
    • Spring Boot Port
    • Introduction of spring boot
    • Spring Boot ide
    • Spring Boot Netty
    • Spring Boot ORM
    • Spring Boot Versions
    • Spring Boot JUnit
    • Spring Boot Keycloak
    • Spring Boot gradle
    • Spring Boot Lombok
    • Spring Boot autowired
    • Spring Boot bean
    • Spring Boot hibernate
    • Spring Boot integration test
    • Spring Boot jdbc
    • Spring Boot MongoDB
    • Spring Boot postgresql
    • Spring Boot rest
    • Spring Boot swagger
    • Spring Boot thymeleaf
    • Spring Boot Unit Test
    • Spring Boot Webflux
    • Spring Boot webclient
    • Spring Boot kubernetes
    • Spring Boot Properties
    • Spring Boot Validation
    • Spring Boot Feature
    • Spring Boot Application
    • Spring Boot email
    • Spring Boot MVC
    • Spring Boot Exception Handling
    • Spring Boot Starter Parent
    • Spring Boot Docker
    • Spring Boot Logging
    • Spring Boot Query
    • Spring Boot Multiple Data Sources
    • Spring Boot Basic Authentication
    • Spring Boot Test
    • Spring Boot jwt
    • Spring Boot Liquibase
    • Spring Boot Prometheus
    • Spring Boot debug
    • Spring Boot GraalVM
    • Spring Boot Batch
    • Spring Boot controller
    • Spring Boot CLI
    • Spring Boot file upload
    • Spring Boot interceptor
    • Spring Boot Service
    • Spring Boot Configuration
    • Spring Boot Datasource Configuration
    • Spring Boot Annotations
    • Spring Boot Starter We
    • Spring Boot Actuator
    • Spring Boot DevTools
    • Spring Boot Repository
    • Spring Boot Dependencies
    • Spring Boot Path Variable
    • Spring Boot Microservices
    • Spring Boot Run Command
    • Spring Boot application.properties
    • Spring Boot Transaction Management
    • Spring Boot Banner
    • Spring Boot JPA
    • Spring Boot Change Port
    • Spring Boot RestTemplate
    • Spring Boot cors
    • Spring Boot HTTPS
    • Spring Boot OAuth2
    • Spring Boot Profiles
    • Spring Boot Interview Questions
    • Spring Boot filter
    • Spring boot logging level
    • Spring Boot Cache
    • Spring Boot Advantages
    • Spring Boot Scheduler
    • Spring Boot Initializr
    • Spring Boot Maven
    • Spring Boot Admin
    • Spring Boot Tomcat
    • Spring Boot WebSocket
    • Spring Boot Executable Jar
    • Spring Boot CommandLineRunner
    • Spring Boot DataSource
    • Spring Batch Scheduler
    • Spring Batch Example
    • Spring Batch Tasklet
    • Spring Batch Admin
    • Spring Batch
    • Spring Boot Qualifier
    • Spring Boot War
    • Spring Boot Test Configuration

Related Courses

Spring Boot Certification Course

Spring Framework Course Training

All in One Data Science Course

Spring Cloud Contract

Spring Cloud Contract

Introduction to Spring Cloud Contract

Spring cloud contract is a project which was used for holding solutions from users to implement the contract approach of consumer-driven. Spring cloud contract is consisting the verifier project of Cloud contract; it is a tool that enables the development of the consumer-driven contract. Cloud contract is written in groovy or YAML and shipped with contract definition language. Contract definition language is used to produce the resources.

What is a spring cloud contract?

  • Cloud contract is a project which helped us to write consumer-driven contracts.
  • Spring cloud contract will ensure that contract between consumer and producer in the application which was distributed. In addition, it will help the message-based and http based interactions.
  • Cloud contract is used to produce the following resources.
  • The JSON stub definition is used in HTTP server stubs at the time of doing integration testing on the code of the client. Test code is written by hand, and test data is produced using a verifier of the cloud contract.
  • We can route messaging using a cloud contract. We are integrating the same with spring integration. We can also set our own integration by using a cloud contract.
  • In cloud contracts, acceptance testing is used to verify whether the implementation of server-side API is compliant with the contract. We can generate full testing by using a cloud contract.
  • Cloud contract is moving TDD for the level of architecture. We can deploy all microservices using the spring cloud test and perform the end to end testing.
  • Spring cloud contract contains very fast feedback as compared to others. We do not require any infrastructure for cloud contracts.
  • Cloud contract will ensure the HTTP messaging stubs that are exactly server-side implementation.
  • It is easy to implement consumer and producer side test cases using cloud contracts. The contract producer is the service exposed to API in the cloud and sends messages.
  • In the cloud, contract consumer is nothing but the service which was used to consume API, which the producer exposed.

How to build a cloud contract?

  • Spring cloud contract is an agreement between consumer and producer, including the following points.
  • The first agreement point includes which endpoints we are using for our application.
  • The second agreement point includes which input we are taking from endpoints.
  • The third agreement point will include how the output looks like.
  • In a cloud contract, a consumer-driven contract is an approach where consumers will drive the changes in API.
  • Once the contract between consumer and producer is established, it will be ensured that it should not break in between.
  • A verifier of cloud contracts is used to enable consumer-driven contracts development.
  • Verifier in cloud contract is used with the contract definition language, which was written in YAML or groovy language.

Spring cloud contract examples

Given below are the examples of the cloud contract.

  • Create project template of cloud contract application by using spring initializer

In the below step, we have provided project group name as com.example, artifact name as springcloudcontract, project name as springcloudcontract, and selected java version as 8.

We have selected spring web and contract verifier dependency in the below project to implement the cloud contract project.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Group – com.example
Artifact name – springcloudcontract
Name – springcloudcontract
Spring boot – 2.6.0
Project – Maven
Project Description - Project for springcloudcontract
Java – 8
Dependencies – contract verifier, spring web
Package name - com.example.springcloudcontract

Spring Cloud Contract output 1

  • After generating project extract files and open this project by using spring tool suite –

After generating the project using the spring initializer in this step, we extract the jar file and open the project using the spring tool suite.

Spring Cloud Contract output 2

  • After opening the project using the spring tool suite, check the project and its files –

In this step, we are checking all the project template files. We also need to check maven dependencies and system libraries.

Spring Cloud Contract output 3

  • Add dependency packages –

In this step, we are adding the contract verifier dependency in the cloud contract project.

Code –

<dependency>   -- Start of dependency tag.
<groupId>org.springframework.cloud</groupId>   -- Start and end of groupId tag.
<artifactId>spring-cloud-starter-contract-verifier</artifactId>  -- Start and end of artifactId tag.
</dependency>    -- End of dependency tag.

Spring Cloud Contract output 4

  • Create producer class –

Code –

public class stud {
public Integer stud_id;
public String stud_name;
}

Spring Cloud Contract output 5

  • Create producer controller class –

Code –

@RestController
public class studcon {
@Autowired
studService studService;
@GetMapping (value = "stud/{stud_id}")
public ResponseEntity<?> getEmployee(@PathVariable("id") int id) {
if (stud.isPresent()) {
return (ResponseEntity<?>) ResponseEntity.status(HttpStatus.OK).contentType (null);
} else {
return ResponseEntity.status (HttpStatus.NOT_FOUND).build();
}
}

Spring Cloud Contract output 6

  • Create consumer class –

Code –

public class cust {
public Integer cust_id;
public String cust_name;
}

output 7

  • Create endpoint cloud contract producer –

Code –

@Component
class custClient {
private String stud_id;
public stud getStud (final int cust_id) {
final RestTemplate restTemplate = new RestTemplate();
final ResponseEntity<stud> result = restTemplate.exchange ("http://localhost:8080/stud/" + stud_id,
HttpMethod.GET, null, stud.class);
return result.getBody ();
}
}

output 8

  • Test the consumer –

Code –

@SpringBootTest(classes = SpringCloudContractConsumerApplication.class)
@AutoConfigureWireMock (port = 808)
@AutoConfigureJson
public class custTest {
@Autowired
custClient cust;
@Autowired
ObjectMapper objmap;
@Test
public void clientShouldRetrunStudForGivenID () throws Exception {
WireMock.stubFor (WireMock.get (WireMock.urlEqualTo ("/stud/1")).willReturn (
WireMock.aResponse ()
.withStatus (100)
.withBody (jsonForStud (new stud (1, "ABC")))));
}
private String jsonForStud (final stud st) throws Exception {
return objmap.writeValueAsString (st);
}
}

output 9

  • Implement producer service contract –

Code –

Contract.make
{
description("After getting request if stud id=1")
request {
method 'GET'
url '/stud/1'
}
response
{
status 100
body("""
{
"stud_id": "1",
"stud_name": "ABC",
}
""")
headers
{
contentType(applicationJson())
}
}

output 10

  • Create a base class –

Code –

public class BClass {
@Autowired
studcon sCont;
@MockBean
private studService sService;
@Before
public void before() {
final stud st = new stud(1, "ABC");
Mockito.when(this.sService.findById(1)).thenReturn(Optional.of(st));
RestAssuredMockMvc.standaloneSetup (this.sCont);
}
}

output 11

  • Build the application –

output 12

  • Run the application –

output 13

Conclusion

Spring cloud contract consumer is nothing but the service which was used to consume API, which the producer exposed. Cloud contract is consisting the verifier project of cloud contract; it is nothing but the tool which enables the development of the consumer-driven contract.

Recommended Articles

This is a guide to Spring Cloud Contract. Here we discuss What is a spring cloud contract and How to build a cloud contract, along with examples. You may also have a look at the following articles to learn more –

  1. spring-boot gradle
  2. spring-boot framework
  3. Spring Boot Admin
  4. Spring boot logging level
Popular Course in this category
Spring Boot Training Program (2 Courses, 3 Project)
  2 Online Courses |  3 Hands-on Projects |  22+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course

Related Courses

All in One Software Development Bundle(600+ Courses, 50+ projects)
Python TutorialC SharpJavaJavaScript
C Plus PlusSoftware TestingSQLKali Linux
Price
View Courses
600+ Online Courses | 50+ projects | 3000+ Hours | Verifiable Certificates | Lifetime Access
4.6 (86,754 ratings)
Spring Framework Training (4 Courses, 6 Projects)4.9
All in One Data Science Bundle (360+ Courses, 50+ projects)4.8
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

C# Programming, Conditional Constructs, Loops, Arrays, OOPS Concept

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more