PDI practice question 26 of 30

A developer wrote Apex code that calls out to an external system using REST API. How should a developer write the test to prove the code is working as intended?

Full set: 201 questions
Answer options
A: Write a class that implements HTTPcalloutMock. Correct answer
B: Write a class that extends webserviceloo.
C: Write a class that implements webservicemock.
D: Write a class that extends HTTPcalloutMock.
Correct Answer:
A. Write a class that implements HTTPcalloutMock.
Explanation

To test Apex code that performs an HTTP callout, such as a REST API call, Salesforce prevents tests from making actual calls to external endpoints. Instead, a mock response must be generated. The standard mechanism for this is to create a class that implements the HttpCalloutMock interface. This interface requires the implementation of a respond method, which intercepts the outbound HttpRequest during the test execution and returns a hard-coded HttpResponse. This allows the developer to test how their code handles various success or failure scenarios without any external dependency.

Why Incorrect

B. Write a class that extends webserviceloo. This is incorrect. WebServiceMock (assuming a typo) is for SOAP callouts, not REST. Also, it is an interface and must be implemented, not extended.
C. Write a class that implements webservicemock. This is incorrect because the WebServiceMock interface is used for testing callouts to SOAP web services, not REST APIs as specified in the question.
D. Write a class that extends HTTPcalloutMock. This is incorrect because HttpCalloutMock is an interface, not a class. In Apex, a class implements an interface; the extends keyword is used for class inheritance.

References

1. Salesforce Apex Developer Guide, "Testing HTTP Callouts":

The documentation states, "To test callouts, you can use mock callouts... To mock callout responses, implement the HttpCalloutMock interface and specify a fake response for the callout." This section provides a clear example of a class implementing HttpCalloutMock.

2. Salesforce Apex Reference Guide, "HttpCalloutMock Interface":

This guide defines the interface: "Use the HttpCalloutMock interface to implement a mock callout response in a test method." It details the required respond(request) method signature that must be implemented.

3. Trailhead, "Apex Testing" Module, "Test Apex Callouts" Unit:

This official training module explains, "To prevent tests from failing and to increase code coverage, Apex provides a built-in mock framework. You can test callouts by using a mock callout. Apex provides the HttpCalloutMock interface for this purpose." It then walks through a practical example of creating a class that implements HttpCalloutMock.

Scroll to Top