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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

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

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Building a REST Service That Collects HTML Form Data Using Netbeans, Jersey, Apache Tomcat, and Java
  • Spring Boot - How To Use Native SQL Queries | Restful Web Services
  • Testing REST Controller Methods With JUnit 5 [Video]
  • Update User Details in API Test Client Using REST Assured [Video]

Trending

  • IoT and Cybersecurity: Addressing Data Privacy and Security Challenges
  • Introduction to Retrieval Augmented Generation (RAG)
  • The Perfection Trap: Rethinking Parkinson's Law for Modern Engineering Teams
  • ITBench, Part 1: Next-Gen Benchmarking for IT Automation Evaluation
  1. DZone
  2. Software Design and Architecture
  3. Integration
  4. Testing Code With REST Calls Made Easy

Testing Code With REST Calls Made Easy

Need to test Spring code that makes remote REST calls? Here's an alternative to mocking frameworks that can speed up test development.

By 
Duncan Brown user avatar
Duncan Brown
·
Aug. 28, 19 · Tutorial
Likes (7)
Comment
Save
Tweet
Share
12.8K Views

Join the DZone community and get the full member experience.

Join For Free

Introduction

These days, our code frequently has to reach out to a remote server as part of its job, usually consuming an API or some other service.

Frequently, our code communicates with these remote services in a RESTful manner.

Writing code in Spring is no different.

Nothing novel about any of this so far.

What do we when we have to create automated tests (unit, integration, or otherwise) that include these service consumers?

A Typical Solution

Odds are, in this case, if you're using Spring, you're making use of its RestTemplate class, which makes remote calls a snap (documentation here).

Now, perhaps the most obvious answer to the above question is to reach for the time-tested option of mocks, and often, this is enough.  With a myriad of options in the Java world alone (Mockito, EasyMock, and JMockit are but a few popular mocking frameworks), it's difficult to go astray.

In the world of Spring, sometimes Dependency Injection can get in the way, especially in some more complex cases where inserting mocks alongside properly managed and wired beans can be a headache.

So is there an alternative?

MockRestServiceServer to the Rescue!

A couple of major versions ago, Spring introduced MockRestServiceServer to help with these very situations.

Instead of injecting mocks and having to manage them, MockRestServiceServer allows you to configure a mock REST service that can intercept outgoing HTTP requests via a series of Matchers  and will instead return some static fixture or response. The best part? It's super simple to use.

Let's take a look at a quick example:

public class MyServiceTest {
  // the service to test
  @Autowired
  private MyService myService;

  // note that this RestTemplate should be the one used by MyService above
  @Autowired
  private RestTemplate restTemplate;

  private MockRestServiceServer mockServer;

  @Before
  public void setUp() {
    this.mockServer = MockRestServiceServer.createServer(this.restTemplate);
  }

  @Test
  public void testMyService() {
    // this can be anything, even loaded from a file
    String serviceResponseBody = "{'field1': 'abcdef', 'field2': 1234 }";
    String url = "https://api.awesome-service.com/api/v1/resource/list";

    this.mockServer.expect(requestTo(url))
    .andExpect(method(HttpMethod.GET))
    .andRespond(withSuccess(serviceResponseBody, MediaType.APPLICATION_JSON));

    // call the service to be tested that calls out to the URL in question
    this.myService.fetchResources();
  }
}

Note that we can perform almost any type of test here, e.g. we could also try calling out to an exposed endpoint that our application has exposed that includes the call to fetchResources().

The code above should be fairly self-explanatory: We set up the mock REST server, configure it, and then call the service under test, and watch the magic! It also fits in nicely with any testing framework you want to use (in this case, JUnit).

The .andRespond(...) portion of the configuration is what tells the mock server what to hand back to the calling code, and takes care of creating proper ResponseEntity objects. 

MockRestServiceServer implements a builder pattern to make configuration, usage, and readability extremely easy, as you can see.

While the mock REST service configuration above is extremely basic, it does the trick.

For additional information on this feature, be sure to check out its Javadoc, including the various kinds of matches that are available to make your mock REST server even more flexible.

Conclusion

If you're using Spring and need to test code that makes remote HTTP calls using the RestTemplate class, then the solution described above is one worth checking out, even in simpler cases of automated testing.

While mocking has its place and isn't going anywhere anytime soon, sometimes taking advantage of a platform's alternatives has its benefits.

REST Web Protocols

Opinions expressed by DZone contributors are their own.

Related

  • Building a REST Service That Collects HTML Form Data Using Netbeans, Jersey, Apache Tomcat, and Java
  • Spring Boot - How To Use Native SQL Queries | Restful Web Services
  • Testing REST Controller Methods With JUnit 5 [Video]
  • Update User Details in API Test Client Using REST Assured [Video]

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!