You need to sign in to do that
Don't have an account?
James Durkee
Need help writing test class for apex class
I'm pretty new to development, and have modified code found elswhere on the internet. The code is working find in my sandbox, but when i attempt to deploy it to production, there's no test classes and so it fails.
Here's the code:
// Use a name besides "lead" otherwise you'll get compilation problems due to symbol collision
public with sharing class leadApexZipCode {
private static boolean isTrigger = false; // Pitfall #4: Used to prevent infinite loops
public class leadException extends Exception {}
/* format from ziptasticapi.com:
{"country":"US","state":"CA","city":"SAN JOSE"}
*/
// Format returned by ziptastic API
public class ziptasticReturn {
string country;
string state;
string city;
}
// Trigger Handler to do zipCodeLookup when new records are created
// Do this after the record is created so we have an ID we can reference
public static void onAfterInsert( List<lead> triggerNew)
{
// Pitfall #4 - Prevent infinite loops
if (isTrigger == true) {
return; // Just return if this is called as a result of our DML operation
} else
isTrigger = true; // Set this so we know we caused ourselves to be called again
// Must pass IDs & not SObjects to @future because the SObject may change by the time @future executes
List<Id> leadsId = new List<Id>();
for (lead a : triggerNew) {
leadsId.add(a.Id);
}
system.debug(LoggingLevel.Info, 'onAfterInsert called with '+triggerNew+'; sending IDs='+leadsId);
makeZipCallout(leadsId);
}
// Pitfall #1 & #2 - Triggers must do callouts from an '@future' and (callout = true) anotated function
@future (callout = true)
private static void makeZipCallout(List<Id>acct)
{
system.debug(LoggingLevel.Info, 'makeZipCallout with '+acct);
string resp;
// Pitfall #3 - Fetch records of the IDs for updating
List<lead> leadSet = [SELECT Id, Postalcode, City, State, Country
FROM lead
WHERE Id = :acct];
for (lead a : leadSet) {
// Note this version of the API is only for the US
string endpoint ='http://ziptasticapi.com/';
endpoint = endpoint + a.Postalcode;
system.debug(LoggingLevel.Info,'zipCode.cls: calling endpoint='+endpoint);
HttpRequest req = new HttpRequest();
HttpResponse res = new HttpResponse();
Http http = new Http();
req.setMethod('GET');
req.setEndpoint(endpoint);
try {
res = http.send(req);
if (res.getStatusCode() != 200) {
throw new leadException(res.getStatus());
}
} catch (leadException e) {
system.debug(LoggingLevel.Error, 'Error HTTP response code = '+res.getStatusCode()+'; calling '+endpoint );
return;
}
resp = res.getBody();
JSONParser parser = JSON.createParser(resp);
parser.nextToken(); // Start object "{"
ziptasticReturn zipInfo = new ziptasticReturn();
// This convenient method reads the JSON stream into a class in one go
zipInfo = (ziptasticReturn) parser.readValueAs(ziptasticReturn.class);
a.State = zipInfo.state;
a.City = zipInfo.city;
a.Country = zipInfo.country;
}
update leadSet; // Call DML operation to update
isTrigger = false; // Pitfall #4 - Trigger is done so reset this
} // makeZipCallout()
}
Here's the code:
// Use a name besides "lead" otherwise you'll get compilation problems due to symbol collision
public with sharing class leadApexZipCode {
private static boolean isTrigger = false; // Pitfall #4: Used to prevent infinite loops
public class leadException extends Exception {}
/* format from ziptasticapi.com:
{"country":"US","state":"CA","city":"SAN JOSE"}
*/
// Format returned by ziptastic API
public class ziptasticReturn {
string country;
string state;
string city;
}
// Trigger Handler to do zipCodeLookup when new records are created
// Do this after the record is created so we have an ID we can reference
public static void onAfterInsert( List<lead> triggerNew)
{
// Pitfall #4 - Prevent infinite loops
if (isTrigger == true) {
return; // Just return if this is called as a result of our DML operation
} else
isTrigger = true; // Set this so we know we caused ourselves to be called again
// Must pass IDs & not SObjects to @future because the SObject may change by the time @future executes
List<Id> leadsId = new List<Id>();
for (lead a : triggerNew) {
leadsId.add(a.Id);
}
system.debug(LoggingLevel.Info, 'onAfterInsert called with '+triggerNew+'; sending IDs='+leadsId);
makeZipCallout(leadsId);
}
// Pitfall #1 & #2 - Triggers must do callouts from an '@future' and (callout = true) anotated function
@future (callout = true)
private static void makeZipCallout(List<Id>acct)
{
system.debug(LoggingLevel.Info, 'makeZipCallout with '+acct);
string resp;
// Pitfall #3 - Fetch records of the IDs for updating
List<lead> leadSet = [SELECT Id, Postalcode, City, State, Country
FROM lead
WHERE Id = :acct];
for (lead a : leadSet) {
// Note this version of the API is only for the US
string endpoint ='http://ziptasticapi.com/';
endpoint = endpoint + a.Postalcode;
system.debug(LoggingLevel.Info,'zipCode.cls: calling endpoint='+endpoint);
HttpRequest req = new HttpRequest();
HttpResponse res = new HttpResponse();
Http http = new Http();
req.setMethod('GET');
req.setEndpoint(endpoint);
try {
res = http.send(req);
if (res.getStatusCode() != 200) {
throw new leadException(res.getStatus());
}
} catch (leadException e) {
system.debug(LoggingLevel.Error, 'Error HTTP response code = '+res.getStatusCode()+'; calling '+endpoint );
return;
}
resp = res.getBody();
JSONParser parser = JSON.createParser(resp);
parser.nextToken(); // Start object "{"
ziptasticReturn zipInfo = new ziptasticReturn();
// This convenient method reads the JSON stream into a class in one go
zipInfo = (ziptasticReturn) parser.readValueAs(ziptasticReturn.class);
a.State = zipInfo.state;
a.City = zipInfo.city;
a.Country = zipInfo.country;
}
update leadSet; // Call DML operation to update
isTrigger = false; // Pitfall #4 - Trigger is done so reset this
} // makeZipCallout()
}
@IsTest
public class LeadApexZipCodeTest {
Static testMethod void testLeadApexZipCode(){
Lead l = new Lead(Name = 'Test');
l.City = 'cityname';
l.State = 'statename';
l.Postalcode = 'yourzipcode';
l.Country = 'countryname';
insert l;
test.startTest();
HttpRequest request = new HttpRequest();
StaticResourceCalloutMock mock = new StaticResourceCalloutMock();
mock.setStaticResource('GoogleMapsAPI');
mock.setStatusCode(200);
mock.setHeader('Content-Type', 'application/json');
mock.respond(request);
HttpResponse response = new HttpResponse();
JSONParser responseParser = JSON.createParser(response.getBody());
// Set the mock callout mode
Test.setMock(HttpCalloutMock.class, mock);
// Call the method that performs the callout
leadApexZipCode.makeZipCallout(l.Id);
}
}