How can we cover attached method. can some help me in this.
#Sales Cloud #Marketing Cloud #Analytics #Nonprofit #Trailhead #Automation #New Releases #Integration #AppExchange
Hi Suraj,
To write a unit test for a @future (callout=true) method, you need to mock the HTTP callout (using HttpCalloutMock) and enclose the execution between Test.startTest() and Test.stopTest(). Salesforce runs all asynchronous methods (like future methods) called within startTest() and stopTest() synchronously right when Test.stopTest() executes.
Here is an example test class structure to cover your method:
1.Create a Mock Callout Class:
Mock Implementation.
Create a mock class that implements HttpCalloutMock to return a fake JSON response simulating your patchCall output (ensuring it contains 'state' => 'Success' and a valid JSON structure with an id field).
2.Prepare Test Data and Context:
Test Setup.
In your test method, insert a test Bid_Review_Request__c record so that the update brUpdate; statement can successfully find and update a record in the database.
3.Wrap in Start/Stop Test:
Execution and Assertion.
Assign your mock, wrap the future method call inside Test.startTest() and Test.stopTest(), and assert that the record was updated successfully.
Apex
@isTest
private class NewProjectHandlerTopUpTest {
// 1. Mock class for HTTP callouts
public class MockHttpResponseGenerator implements HttpCalloutMock {
public HTTPResponse respond(HTTPRequest req) {
HttpResponse res = new HttpResponse();
res.setHeader('Content-Type', 'application/json');
res.setStatusCode(200);
// Construct JSON response matching the parser requirements
res.setBody('{"state": "Success", "resBody": "{\\"id\\": \\"12345\\"}"}');
return res;
}
}
@isTest
static void testNewProjectHandlerTopUp() {
// Create test record to satisfy update operation
Bid_Review_Request__c testReq = new Bid_Review_Request__c(
Name = 'Test Project'
// Add required fields for Bid_Review_Request__c here
);
insert testReq;
Map<String, String> recordMap = new Map<String, String>{
'ID' => testReq.Id,
'Name' => 'Test Project'
};
// Set mock callout
Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
Test.startTest();
// Calling the future method
YourClassName.newProjectHandlerTopUp(recordMap, '{"test":"json"}', 'destination', 'WBS123');
Test.stopTest(); // Future method executes here
// Assertions to verify the record was updated
Bid_Review_Request__c updatedReq = [SELECT WBS_Project__c FROM Bid_Review_Request__c WHERE Id = :testReq.Id];
System.assertEquals('12345', updatedReq.WBS_Project__c, 'The WBS Project code should be updated successfully.');
}
}
(Note: Replace YourClassName with the actual name of the Apex class containing your future method).