You need to sign in to do that
Don't have an account?
Tanner Russell
I need help testing an async callout
I am not sure how to test an async callout and have not had any luck looking at other posts. I am new to apex so i would appreciate any help, my class is below split into 2 methods due to a conflicting trigger. I need the future due to the 10 second cpu limitation and i need to update 2.5k rows of data based on the json it works when i run it pn my test site but i cant get the test coverage.
public class JSONPullData {
public static List<Contract> con2;
public static HttpResponse response;
// @future(callout=true)
public static HttpResponse parseJSONResponse() {
update con2;
return response;
}
@future(callout=true)
public static void processData(){
//Setup the connection to the json to pull in
JsonUtil Jutil = new JsonUtil();
Http httpProtocol = new Http();
// Create HTTP request to send.
HttpRequest request = new HttpRequest();
// Set the endpoint URL.
request.setEndPoint('url');
// Set the HTTP verb to GET.
request.setMethod('GET');
// Send the HTTP request and get the response.
// The response is in JSON format.
response = httpProtocol.send(request);
if(response.getStatusCode() == 200){
//System.debug(response.getBody());
//deserialize the json
List<Object> eqt = (List<Object>) JSON.deserializeUntyped(response.getBody());
//add the street address to the set the set cannot have duplicates so the street must be unique
Map<string,string> st = new Map<string,string>();
Map<string,Double> stRent = new Map<string,Double>();
for (Object o : eqt){
Map<String,Object> mapobj = (Map<string,Object>)o;
st.put((String)mapobj.get('Street'),(String)mapobj.get('Date'));
stRent.put((String)mapobj.get('Street'),(Double)mapobj.get('Rent'));
}
//find all the space names that match the street in the set
// System.debug(st);
Map<ID,Contract> con = new Map<ID,Contract>([Select id, Space__r.Name,Current_Rental_Rate__c, Space__c from Contract where Space__r.Name IN :st.keySet() and Active__c = TRUE]);
//create a list of spaces that are connected to the leases
List<Space__c> s = [Select id,Name,Active_Contract__c from Space__c where Active_Contract__c IN :con.keySet()];
//System.debug(s);
//create maps to locate the data
Map<id, Double> holdLease = new Map<id, Double>();
Map<id, Date> holdDate = new Map<id, Date>();
for(Space__c c: s){
//for (Object o : eqt){
// Map<string,Object> mapobj = (Map<string,Object>)o;
// if(c.Name == (String)mapobj.get('Street')){
// System.debug((String)mapobj.get('Renewal Date'));
//map the rent and renewal date
System.debug(c.Name);
Date d = date.parse(st.get(c.Name));
holdDate.put(c.Active_Contract__c, d);
holdLease.put(c.Active_Contract__c, stRent.get(c.Name));
}
//}
con2 = [Select id, Space__r.Name,Name,Current_Rental_Rate__c, Space__c from Contract where id in :holdLease.keySet()];
// System.debug(con2);
//
//set up email
Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
message.setSenderDisplayName('Salesforce Support');
message.toAddresses = new String[] { 'email@email.com' };
message.optOutPolicy = 'FILTER';
message.subject = 'Log Updated Rent for lease rr';
String mess = '';
mess = mess + 'Lease ID - Lease Name - Space Name - Rent' + '</br></br>';
for(Contract c: con2){
if(holdLease.containsKey(c.id)){
//modify the values
mess = mess + c.id + ' - ' + c.Name + ' - ' + c.Space__r.Name + ' - ' + c.Current_Rental_Rate__c + '</br>';
c.Current_Rental_Rate__c = holdLease.get(c.id);
c.Renewal_Date__c = holdDate.get(c.id);
}
}
message.setHtmlBody(mess);
Messaging.SingleEmailMessage[] messages = new List<Messaging.SingleEmailMessage> {message};
Messaging.SendEmailResult[] results = Messaging.sendEmail(messages);
JSONPullData.parseJSONResponse();
}
}
}
@isTest
private class JsonPullDataCallout_Test {
@isTest static void testCallout() {
// Set mock callout class
Test.setMock(HttpCalloutMock.class, new JsonPullData_Test());
// Call method to test.
// This causes a fake response to be sent
// from the class that implements HttpCalloutMock.
Test.startTest();
JSONPullData.processData();
Test.stopTest();
HttpResponse res = JSONPullData.response;
// Verify response received contains fake values
String contentType = res.getHeader('Content-Type');
System.assert(contentType == 'application/json');
String actualValue = res.getBody();
String expectedValue = '[{"Street":"123 Test Road","Rent":1356.95,"Date":"1/9/2017"}]';
System.assertEquals(actualValue, expectedValue);
System.assertEquals(200, res.getStatusCode());
}
}
@isTest
global class JsonPullData_Test implements HttpCalloutMock {
// Implement this interface method
public static HTTPResponse res;
global HTTPResponse respond(HTTPRequest req) {
// Optionally, only send a mock response for a specific endpoint
// and method.
System.assertEquals('url', req.getEndpoint());
System.assertEquals('GET', req.getMethod());
// Create a fake response
HttpResponse res = new HttpResponse();
res.setHeader('Content-Type', 'application/json');
res.setBody('[{"Street":"123 Test Road","Rent":1356.95,"Date":"1/9/2017"}]');
res.setStatusCode(200);
return res;
}
}
public class JSONPullData {
public static List<Contract> con2;
public static HttpResponse response;
// @future(callout=true)
public static HttpResponse parseJSONResponse() {
update con2;
return response;
}
@future(callout=true)
public static void processData(){
//Setup the connection to the json to pull in
JsonUtil Jutil = new JsonUtil();
Http httpProtocol = new Http();
// Create HTTP request to send.
HttpRequest request = new HttpRequest();
// Set the endpoint URL.
request.setEndPoint('url');
// Set the HTTP verb to GET.
request.setMethod('GET');
// Send the HTTP request and get the response.
// The response is in JSON format.
response = httpProtocol.send(request);
if(response.getStatusCode() == 200){
//System.debug(response.getBody());
//deserialize the json
List<Object> eqt = (List<Object>) JSON.deserializeUntyped(response.getBody());
//add the street address to the set the set cannot have duplicates so the street must be unique
Map<string,string> st = new Map<string,string>();
Map<string,Double> stRent = new Map<string,Double>();
for (Object o : eqt){
Map<String,Object> mapobj = (Map<string,Object>)o;
st.put((String)mapobj.get('Street'),(String)mapobj.get('Date'));
stRent.put((String)mapobj.get('Street'),(Double)mapobj.get('Rent'));
}
//find all the space names that match the street in the set
// System.debug(st);
Map<ID,Contract> con = new Map<ID,Contract>([Select id, Space__r.Name,Current_Rental_Rate__c, Space__c from Contract where Space__r.Name IN :st.keySet() and Active__c = TRUE]);
//create a list of spaces that are connected to the leases
List<Space__c> s = [Select id,Name,Active_Contract__c from Space__c where Active_Contract__c IN :con.keySet()];
//System.debug(s);
//create maps to locate the data
Map<id, Double> holdLease = new Map<id, Double>();
Map<id, Date> holdDate = new Map<id, Date>();
for(Space__c c: s){
//for (Object o : eqt){
// Map<string,Object> mapobj = (Map<string,Object>)o;
// if(c.Name == (String)mapobj.get('Street')){
// System.debug((String)mapobj.get('Renewal Date'));
//map the rent and renewal date
System.debug(c.Name);
Date d = date.parse(st.get(c.Name));
holdDate.put(c.Active_Contract__c, d);
holdLease.put(c.Active_Contract__c, stRent.get(c.Name));
}
//}
con2 = [Select id, Space__r.Name,Name,Current_Rental_Rate__c, Space__c from Contract where id in :holdLease.keySet()];
// System.debug(con2);
//
//set up email
Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
message.setSenderDisplayName('Salesforce Support');
message.toAddresses = new String[] { 'email@email.com' };
message.optOutPolicy = 'FILTER';
message.subject = 'Log Updated Rent for lease rr';
String mess = '';
mess = mess + 'Lease ID - Lease Name - Space Name - Rent' + '</br></br>';
for(Contract c: con2){
if(holdLease.containsKey(c.id)){
//modify the values
mess = mess + c.id + ' - ' + c.Name + ' - ' + c.Space__r.Name + ' - ' + c.Current_Rental_Rate__c + '</br>';
c.Current_Rental_Rate__c = holdLease.get(c.id);
c.Renewal_Date__c = holdDate.get(c.id);
}
}
message.setHtmlBody(mess);
Messaging.SingleEmailMessage[] messages = new List<Messaging.SingleEmailMessage> {message};
Messaging.SendEmailResult[] results = Messaging.sendEmail(messages);
JSONPullData.parseJSONResponse();
}
}
}
@isTest
private class JsonPullDataCallout_Test {
@isTest static void testCallout() {
// Set mock callout class
Test.setMock(HttpCalloutMock.class, new JsonPullData_Test());
// Call method to test.
// This causes a fake response to be sent
// from the class that implements HttpCalloutMock.
Test.startTest();
JSONPullData.processData();
Test.stopTest();
HttpResponse res = JSONPullData.response;
// Verify response received contains fake values
String contentType = res.getHeader('Content-Type');
System.assert(contentType == 'application/json');
String actualValue = res.getBody();
String expectedValue = '[{"Street":"123 Test Road","Rent":1356.95,"Date":"1/9/2017"}]';
System.assertEquals(actualValue, expectedValue);
System.assertEquals(200, res.getStatusCode());
}
}
@isTest
global class JsonPullData_Test implements HttpCalloutMock {
// Implement this interface method
public static HTTPResponse res;
global HTTPResponse respond(HTTPRequest req) {
// Optionally, only send a mock response for a specific endpoint
// and method.
System.assertEquals('url', req.getEndpoint());
System.assertEquals('GET', req.getMethod());
// Create a fake response
HttpResponse res = new HttpResponse();
res.setHeader('Content-Type', 'application/json');
res.setBody('[{"Street":"123 Test Road","Rent":1356.95,"Date":"1/9/2017"}]');
res.setStatusCode(200);
return res;
}
}
How much is the coverage you have now - I also see, only the success scenario is being tested here. Try to test the failures as well other than code 200.