Writing Test Classes for Invocable and @Future Apex Methods

Question
How Can I Write Test Classes for an Invocable Apex Class and an @Future Callout Class?
I am new to Apex and eager to learn. I have two classes that work as intended, but I am struggling to create test classes for them since I have never written test classes before. Writing test classes for Invocable and @Future Apex methods can be particularly challenging. Knowing how to write test classes for Invocable and @Future Apex methods can greatly improve your debugging efficiency and code quality.
- Invocable Apex Class: This class is triggered by a Process Builder when a Lead record meets specific criteria. It sends lead details, such as ID, Email, First Name, and Last Name, to another class.
- @Future Apex Class: This class performs a POST HTTP callout to an external system using the lead data. It receives an ID in the API response, which it then updates on the Lead record.
I need help understanding how to write effective test classes to validate these functionalities.
Answer
Testing an Invocable Apex class and an @Future method that performs an HTTP callout involves creating mock data, simulating the HTTP response, and validating that the logic behaves as expected. Here’s the breakdown of the scenario and the solution:
Advance your career with professional Salesforce training in Chicago—attend our free demo and take the first step toward certification..!
You have two classes:
- Invocable Apex Class: This class is called by a Process Builder or Flow. It receives a list of leads, extracts data, and invokes an @Future method for a callout.
- @Future Callout Class: This class makes a POST HTTP callout to an external system using the lead data. The response includes an ID, which is then updated on the lead record.
To test these classes, you need to handle two challenges:
- Simulating the HTTP callout using a
HttpCalloutMock
class. - Writing a test class to enqueue the future method and validate the results.
Here’s how you can achieve this when writing test classes for Invocable and @Future Apex methods:
Test Class for the Invocable and @Future Callout Classes
The test class uses mock data and an HTTP callout mock to simulate external API behavior. It verifies whether the lead record is updated correctly after the callout.
@isTest
class MakeCalloutTest {
// A simple HTTP mock class to simulate an external API response
class EchoHttpMock implements HttpCalloutMock {
HttpResponse response;
EchoHttpMock(HttpResponse res) {
response = res;
}
public HttpResponse respond(HttpRequest req) {
return response;
}
}
@isTest
static void testInvocableAndFutureCallout() {
// Step 1: Create mock lead data
List<Lead> leads = new List<Lead>{
new Lead(LastName = 'Test', Company = 'Test Company')
};
insert leads;
// Step 2: Simulate the HTTP callout response
HttpResponse mockResponse = new HttpResponse();
mockResponse.setBody('<?xml version="1.0" encoding="utf-8"?><root U_Id="12345"></root>');
mockResponse.setStatusCode(200);
Test.setMock(HttpCalloutMock.class, new EchoHttpMock(mockResponse));
// Step 3: Start test and invoke the invocable method
Test.startTest();
MakeCallout.invokeleadcallout(leads);
Test.stopTest();
// Step 4: Validate that the lead was updated with the correct ID
Lead updatedLead = [SELECT Id__c FROM Lead WHERE Id = :leads[0].Id];
System.assertEquals('12345', updatedLead.Id__c, 'The ID__c field was not updated correctly.');
}
@isTest
static void testCalloutExceptionHandling() {
// Step 1: Simulate an error response for the callout
HttpResponse errorResponse = new HttpResponse();
errorResponse.setStatusCode(500);
errorResponse.setBody('{"error": "Internal Server Error"}');
Test.setMock(HttpCalloutMock.class, new EchoHttpMock(errorResponse));
// Step 2: Create mock lead data
List<Lead> leads = new List<Lead>{
new Lead(LastName = 'ErrorTest', Company = 'Error Test Company')
};
insert leads;
// Step 3: Start test and invoke the invocable method
Test.startTest();
MakeCallout.invokeleadcallout(leads);
Test.stopTest();
// Step 4: Validate that no updates were made to the lead
Lead unchangedLead = [SELECT Id__c FROM Lead WHERE Id = :leads[0].Id];
System.assertNull(unchangedLead.Id__c, 'The ID__c field should not be updated for a failed callout.');
}
}
Explanation of the Test Class
- Mocking the HTTP Response: The
EchoHttpMock
class implements theHttpCalloutMock
interface, allowing you to simulate API responses for both success and error cases. This is crucial when writing test classes for Invocable and @Future Apex methods. - Creating Test Data: The test class creates and inserts lead records to work with during the test execution.
- Simulating the Callout: The
Test.setMock
method specifies the mocked HTTP response for the callout. - Testing Logic: The test cases invoke the invocable method, enqueue the future method, and validate the final state of the lead records.
- Handling Exceptions: A separate test ensures that the catch block in the
@future
method handles errors correctly and does not update lead records when the callout fails.
This approach covers both the success and error scenarios, ensuring that your classes are thoroughly tested.
See also: Salesforce Identity Management Interview Questions
Elevate Your Career with Salesforce Training in Chicago
Our Salesforce training provides an engaging, hands-on approach to help you master essential skills for success in the CRM industry. The program focuses on Salesforce Admin, Developer, and AI modules, blending theoretical concepts with practical, real-world applications. Through live projects and interactive assignments, you’ll develop the expertise needed to address complex business scenarios using Salesforce solutions. Guided by experienced instructors, you’ll gain both technical skills and valuable industry knowledge to advance your career.
Additionally, our Salesforce Training Program in Chicago offers personalized mentorship, certification exam preparation, and interview coaching to help you stand out in a competitive job market. You’ll benefit from extensive study materials, hands-on experience with live projects, and ongoing support throughout the program. By the course’s end, you’ll be equipped for certification exams, with practical problem-solving abilities that employers prioritize.
Start your Salesforce journey today and open doors to exciting career prospects! Join our FREE demo class now to get started..!!!
Related links:
List Class in Salesforce Apex
Synchronous vs. Asynchronous Apex
Detailed Guide to Triggers in Salesforce
Understanding Apex Classes and Objects in Simple Terms
Salesforce Apex Code Best Practices
Understanding Control Structures in Apex
How to Effectively Write Apex Unit Tests?
Easy way to Methods and Functions in Apex
Detailed Guide to Contains Method in Salesforce Apex
A Deep Dive into Queueable Apex in Salesforce