How to create test data in apex using Mock API Responses? In Apex, when you’re working with HTTP callouts—like hitting a weather API—you can’t make real external calls in test methods. Salesforce enforces this to ensure your tests are reliable, fast, and independent of external systems.
But how do you test those callout methods?
That’s where HttpCalloutMock comes in. It allows you to simulate API responses and build reliable, realistic unit tests.
Create Test Data in Apex Using Mock API Responses
In this article, we’ll walk through a full example: calling a mock weather API and writing a proper test for it using HttpCalloutMock.
Step 1: Create the Main Apex Class
Let’s say you have a simple class called WeatherApp that calls an external weather API and returns the response body:
This class does a GET request to a weather API and returns the result. But this can’t be tested as-is, because http.send() will throw an error in test context unless mocked.
Also Read: How to Call an Apex Class from a Data Mapper in OmniStudio?
Step 2: Create the Test Class and Mock Response
To properly test this class, we’ll need two things:
- A mock implementation of the API using HttpCalloutMock
- A test method that uses this mock to validate the response
Here’s how you can do both inside a single test class file:
How Does It Work?
When the test method runs and calls WeatherApp.getWeather(), the Http.send() line would normally make a real callout — but because we used Test.setMock(…), Salesforce intercepts that call and instead uses our WeatherMock.respond() method.
That means:
- No actual call is made to https://api.weatherapi.com/data
- The mock respond() method is called
- It returns a fake, controlled response (25C, Sunny)
This keeps your test fast, isolated, and consistent — regardless of the actual availability of the API.
Why Use Mocks?
Mocking callouts in Apex tests has major advantages:
- Avoids hitting real APIs during unit tests
- Tests different scenarios (success, failure, timeouts) easily
- Keeps test results consistent and reliable
- Required by Salesforce — test methods cannot make callouts directly
Wrapping Up
That’s how you create test data in Apex using a mock API response. By implementing HttpCalloutMock and using Test.setMock, you can simulate callouts and verify how your code responds — without ever leaving the Salesforce platform.