top of page
1 July 2024
08 Min. Read

Mocking & Stubbing in API Integration Testing

Mocking & Stubbing in API Integration Testing

Fast Facts

Get a quick overview of this blog

  1. Use mocks and stubs to isolate your application's code from external services.

  2. Employ mocks and stubs to create various scenarios, including error conditions, for comprehensive testing.

  3. While mocks and stubs are valuable, avoid over-reliance. Combine them with occasional real-world testing for robust integration coverage.

"Using mocks and stubs in our API integration tests has drastically improved our test reliability. We can now simulate various edge cases and ensure our service handles them gracefully."

-John Doe, Senior Engineer


As engineering managers, we all crave reliable, fast, and efficient testing.


Integration testing is a key solution to test all those tiny services when 1000s of them are interacting with each other in a complex setup like Netflix.


But what comes as a problem in such a situation?


Every service is talking to one external service or to say the least, with the database. Having 1000s of such databases and services, up and running to proceed this communication is the issue.


And here comes mocking and stubbing as an effective solution. Instead of letting the real db and service live, mocking them out for the test purpose always helps.


What is API Integration Testing?


API integration testing is a type of software testing that focuses on verifying how well different systems communicate with each other through APIs (Application Programming Interfaces). It essentially checks if the data exchange between these systems happens smoothly and as intended.


Here's a scenario to illustrate:

API integration testing

Imagine an e-commerce website that integrates with a payment gateway API. When a customer places an order and chooses to pay, the website would send the order details (products, price, etc.) to the payment gateway API. This API would then handle the secure payment processing and send a confirmation back to the website.

💡 API integration testing in this scenario would involve creating tests that:

1. Simulate the website sending order data to the payment gateway API.
2. Verify that the API receives the data correctly and in the expected format.
3. Check if the API interacts with the payment processor as intended (e.g., sending payment requests, handling authorization).
4. Ensure the API sends a successful confirmation response back to the website.
5. Test what happens in case of errors (e.g., insufficient funds, network issues).

By testing this integration thoroughly, you can ensure a smooth checkout experience for customers and avoid issues where orders fail due to communication problems between the website and the payment gateway.

Quick Question

Are you Planning to Automate your Integration Testing?

Introduction to Mocking and Stubbing


Mocking and stubbing are techniques used to simulate the behavior of real objects. They help in isolating the system under test and provide controlled responses. These techniques are particularly useful in API integration testing, where dependencies on external systems can make testing complex and unreliable.

Mocking refers to creating objects that mimic the behavior of real objects. They record interactions, which can be verified later to ensure the system behaves as expected.

Get to know about auto-generated mocks approach here.

Stubbing involves providing predefined responses to method calls made during the test. Unlike mocks, stubs do not record interactions; they simply return the expected output.

Why Mock and Stub in API Integration Testing?

According to a survey by TechBeacon, 70% of development teams use mocking and stubbing in their integration tests.
  • Isolation: 

    Isolate the component under test from external dependencies.

  • Control:

    Provide controlled responses and scenarios for testing edge cases.

  • Speed:

    Reduce the time taken to run tests by eliminating dependencies on external systems.

  • Reliability:

    Ensure consistent test results by avoiding flaky external dependencies.


Scenario


Imagine you're developing a social media scheduling application that integrates with a weather API and a fictional content delivery network (CDN) called "Nimbus." During integration testing, you want to isolate your application's code from these external services. This ensures your tests focus on the functionality of your scheduling logic, independent of any external factors. Mocking and stubbing come in handy here.


➡️Mocking Weather API


Use Case: 

Your application relies on a weather API to schedule social media posts based on weather conditions.


Mocking: 

Within your integration tests, leverage a mocking framework to generate simulated responses for weather API calls. This enables testing various scenarios, like sunny days or rainy forecasts, without interacting with a real weather service.


Example: 

Consider this weather API endpoint (GET request) for a specific location:

GET https://api.weather.com/v1/forecasts/hourly/3day?geocode=40.7128,-74.0059
Mocked Sunny Day Response:
{
  "location": {
    "name": "New York City, NY"
  },
  "forecast": [
    { "period": 0, "conditions": "Sunny", "temperature": 78 },
    { "period": 1, "conditions": "Clear Skies", "temperature": 65 },
    // ... (other hourly forecasts for 3 days)
  ]
}
Mocked Rainy Day Response (for testing alternative scenarios):
{
  "location": {
    "name": "New York City, NY"
  },
  "forecast": [
    { "period": 0, "conditions": "Rain", "temperature": 52 },
    { "period": 1, "conditions": "Scattered Showers", "temperature": 50 },
    // ... (other hourly forecasts for 3 days)
  ]
}

➡️Stubbing Nimbus CDN API


Use Case: 

Your application interacts with the Nimbus CDN API to upload and schedule social media content for delivery.


Stubbing: 

During integration tests, create stubs that mimic the expected behavior of the Nimbus CDN API. These stubs provide predefined responses to your application, simulating the functionality of uploading and scheduling content without requiring a live connection to the actual Nimbus service.


Advantages: 

Stubbing the Nimbus CDN API ensures your integration tests are not affected by the availability or changes in the external service. This allows you to focus solely on testing your application's logic for scheduling content delivery.


Benefits of Mocking and Stubbing:


  • Isolation: 

    Mocks and stubs isolate your application's code from external dependencies. This allows you to test your app's logic in a controlled environment, independent of the availability or behavior of external services. Going back to the food delivery app, you can mock the Restaurant API to test your order processing logic without placing real orders or stub the Payment Gateway to verify how your app handles successful or failed transactions without processing actual payments.


  • Speed and Reliability: 

    Tests that interact with external services can be slow and unreliable due to network delays or external service outages. By mocking and stubbing, you can create predictable responses, making your tests faster and more reliable. Mocking the Restaurant API ensures your tests run quickly without waiting for real API responses, and stubbing the Payment Gateway guarantees consistent test results regardless of the payment gateway's actual state.


  • Testing Edge Cases: 

    Mocks and stubs allow you to simulate various scenarios, including error conditions or unexpected responses from external services. In the food delivery app example, you could mock the Restaurant API to return an empty menu (testing how your app handles unavailable items) or stub the Payment Gateway to simulate a declined transaction (ensuring your app gracefully handles payment failures).


Pain Points of Mocking and Stubbing:

Imagine your mocks are like training wheels on a bike. They help you get started, but if you never take them off, you'll never learn to ride on your own.
  • Over-Mocking: 

    Over-reliance on mocks and stubs can lead to a situation where your tests don't accurately reflect the real-world behavior of your application. For instance, if you always mock the Restaurant API to return successful responses, you might miss potential bugs in your app's code that arise when encountering actual errors from the API.


  • False Positives: 

    Mocks and stubs that are not carefully designed can lead to false positives in your tests. If a mock or stub always returns a predefined successful response, your tests might pass even if there are underlying issues in your application's logic for handling real-world scenarios.


  • Learning Curve: 

    Using mocking and stubbing frameworks effectively can have a learning curve for developers. Understanding the concepts and choosing the right tools can take some time and practice.


  • Maintenance Overhead: 

    Mocking and stubbing can be great for initial tests, but keeping them up-to-date with the ever-evolving real services can be a burden.


💡 How HyperTest solves this problem?
HyperTest mocks external components and auto-refreshes mocks when dependencies change behavior.

Want to learn more about this approach? Click here.

Conclusion


Mocking and stubbing are powerful tools for integration testing, but they should be used judiciously. By understanding their benefits and pain points, you can leverage them to write efficient and reliable tests that ensure the smooth integration of your application with external services. Remember, a balanced approach that combines mocks and stubs with occasional tests against real external services can provide the most comprehensive test coverage for your integration points.

Related to Integration Testing

Frequently Asked Questions

1. What is stubbing in API integration testing?

Stubbing in API integration testing involves creating lightweight substitutes for external APIs. These stubs provide pre-defined responses to your application's requests, mimicking the behavior of the real API without actual interaction. This allows you to test your application's logic in isolation and control how it reacts to different scenarios.

2. What is mocking in API integration testing?

Mocking in API integration testing uses a mocking framework to create more sophisticated simulations of external APIs. Mocks can not only provide pre-defined responses but also verify how your application interacts with them. They can check if your code calls the API with the correct parameters and handle different response formats.

3. Can stubs and mocks be used together in API testing?

Absolutely! Stubs and mocks can be powerful allies in API testing. You can use stubs for simpler interactions where just the response data matters. Meanwhile, mocks are ideal for complex scenarios where verifying how your application interacts with the API is crucial.

For your next read

Dive deeper with these related posts!

What Is Integration Testing? Types, Tools & Examples
13 Min. Read

What is Integration Testing

How Integration Testing Improve Your Software?
07 Min. Read

How Integration Testing Improve Your Software?

Boost Dev Velocity with Automated Integration Testing
05 Min. Read

Boost Dev Velocity with Automated Integration Testing

bottom of page