To mock callouts in Apex, you can create a class that implements the HttpCalloutMock
interface. This allows you to define the desired response for an HTTP request made during testing. Here’s an example of how you can create a mock class for callouts:
private class RestMock implements HttpCalloutMock {
public HTTPResponse respond(HTTPRequest req) {
HTTPResponse res = new HTTPResponse();
res.setHeader('Content-Type', 'text/json');
res.setBody('{}');
res.setStatusCode(200);
return res;
}
}
In your test method, you can use the Test.setMock
method to associate your mock class with the HTTP callout. Here’s an example of how to use the mock in a test:
@isTest static void myTest() {
Test.setMock(HttpCalloutMock.class, new RestMock());
// Some stuff...
Test.startTest();
// Test-related stuff...
Test.stopTest();
}
By using this approach, you can simulate different scenarios and responses to ensure your code handles callouts correctly during testing.