DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Software Design and Architecture
  3. Integration
  4. Performing Integration Tests on REST Services

Performing Integration Tests on REST Services

Look at performing integration tests on REST services using mock server and expectations for Spring Boot applications.

Aritra Nag user avatar by
Aritra Nag
·
Nov. 19, 18 · Tutorial
Like (19)
Save
Tweet
Share
66.87K Views

Join the DZone community and get the full member experience.

Join For Free

Basics of Testing and Types

There are three basic layers of testing:

  • Unit test — making sure each function/unit of code works as expected
  • Functional test — making sure units interact with each other as expected
  • Integration test — making sure our app integrate with other app/api/services as expected

Mock server helps with all layers of tests, although it is particularly useful for functional and integration.

Mock Server can be used for mocking any system you integrate with via HTTP or HTTPS (i.e. services, websites, etc).

When Mock Server receives a request, it matches the request against active expectations that have been configured.

An expectation defines the action that is taken, for example, a response could be returned.

MockServer supports the following actions:

  • Return a “mock” response when a request matches an expectation.Response Action Expectation
  • Return an invalid response or close the connection when a request matches an expectation.Error Action Expectation

MockServer allows you to mock any server or service that you connect to over HTTP or HTTPS, such as a REST or RPC service.

This is useful in the following scenarios:

  • Testing
    • Easily recreate all types of responses for HTTP dependencies such as REST or RPC services to test applications easily and effectively.
    • Easily setup mock responses independently for each test to ensure test data is encapsulated with each test. Avoid sharing data between tests that are difficult to manage and maintain and risks tests infecting each other
    • Create test assertions that verify the requests the system-under-test has sent

Mocking Dependencies and Verifying Request

A system with service dependencies, as follows:

System In Production

MockServer could be used to mock the service dependencies, as follows:

Mocking service dependencies with MockServer

We will demonstrate this architecture by the following approach.

  1. Simple CRUD Spring Boot application.
  2. An Consumer Service to using the above application.

We will create expectations class and methods in the consumer service to mock the requests and responses that we need from the CRUD Spring Boot application.

Technical Specs:

  • Spring boot app
  • Java 8
  • H2
  • Mock Server
  • Junits

Implementations

In the CRUD application, we have 2 endpoints for "Add a Product" and "Get the Product Details."

Sample Add Product JSON:

{
“productName”: “Test1”,
“productType”: “Test1”
}

Sample GET Products JSON:

[{
“productId”: “1”,
“productName”: “Test”,
“productType”: “Test”,
“port”: 8000,
“links”: [{
“rel”: “self”,
“href”: “http://localhost:8000/db/getproduct/1”
}]},{
“productId”: “2”,
“productName”: “Test1”,
“productType”: “Test1”,
“port”: 8000,
“links”: [{
“rel”: “self”,
“href”: “http://localhost:8000/db/getproduct/2”
}]}]

In the "Consumer Service," we have the following simple REST Template Invocation for adding and getting products.

Getting Product Details

productsObject = (Object) restTemplate
.exchange(builder.toUriString(), HttpMethod.GET, httpEntity, String.class).getBody();


Adding Product

HttpEntity<String> entity = new HttpEntity<String>(gson.toJson(product), headers);

restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class);



The above implementations are enough to consume the endpoints of the CRUD applications to suit our requirements.

MOCK Server Usage and Unit Tests:

The main benefit is that the mock server is operated and maintained for the benefit of the development team, so you can make it as simple or as complex as you need it to.

We need to implement the following in the Consumer Service to mock the request/responses


Adding Maven Dependencies

<!-- https://mvnrepository.com/artifact/org.mockito/mockito-all -->
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.9.5</version>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.mock-server</groupId>
<artifactId>mockserver-netty</artifactId>
<version>3.10.7</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>





We need to add the above dependencies in the Maven POM to use the API's of Mock Server.


Initializing Mock Server

Capture

We can externalize the PORT number and other URL details and inject them while executing the test suites.

Creating Expectations

We need to add the following code in the Static Methods of Setup JUNIT Class for adding and getting products

Capture

The above code helps to set the mock server specifications and also helps to understand what consumers should expect in case of integration tests.

Implementing Test Cases

Capture

In the above way, we can bypass the REST calls to be CRUD applications and do the integration tests in the consumer service.

Github Repository for the codes:

https://github.com/aritnag/mockserver-springboot-examples

Summary

We have learned:

  • Why, What, How of mock server
  • Integrating Junits with Mock Server
  • Spring Boot Test Cases with Rest Template
unit test REST Web Protocols Integration Spring Framework

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Playwright vs. Cypress: The King Is Dead, Long Live the King?
  • When AI Strengthens Good Old Chatbots: A Brief History of Conversational AI
  • Three SQL Keywords in QuestDB for Finding Missing Data
  • How to Cut the Release Inspection Time From 4 Days to 4 Hours

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: