+ Start a Discussion
Beltran BajaBeltran Baja 

How to write Test Class for simple Apex Class and Trigger

Hi guys, I'm wondering of how I am going to write a Test Class for Apex Class and a Trigger. This is just a simple Class and a Trigger please see below exact codes I am using.

trigger LeadUpdateListener on Lead (after update) {

    for ( Lead updatedLead : Trigger.New ) {
        CalloutExternal.pipelineConnect(updatedLead.Id);
	}
    
}
public class CalloutExternal {

    @future(callout=true)
    
    public static void pipelineConnect (String id) {
        
        String token = 'xxxxxxxxx';
        
        HttpRequest request = new HttpRequest();
        String endpoint = 'https://xxx.xxxxxxx.com/trigger/'+ token + '/' + id;
        request.setEndpoint(endpoint);
        request.setMethod('GET');
               
        HttpResponse response = new HTTP().send(request);
        
        System.debug('xxxx Response...' + response);
    }

}
I tried creating a Test Class but it doesn't let me through. If anyone who could show me here that would be much appreciated. Thank you!
Best Answer chosen by Beltran Baja
karthikeyan perumalkarthikeyan perumal
Hello,

kinldy find the Test class for your callout trigger, 

First you need to create mock Response generatore class since your using call out in your trigger. 

Mock reponse class: 
 
@isTest
global class MockHttpResponseGenerator implements HttpCalloutMock {
    // Implement this interface method
    global HTTPResponse respond(HTTPRequest req) {
         
        // Create a fake response
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'application/json');
        res.setBody('{"example":"test"}');
        res.setStatusCode(200);
        return res;
    }
}

after creating this class you need to create  test class for your trigge. 
 
@isTest
public class TestLeadUpdateListener
{
 public static testMethod void TestLeadUpdate()
 {
   Lead temleadobj= new lead();
   temleadobj.LastName='TestChecking';
   temleadobj.Company='Testing';
   temleadobj.Status='Open - Not Contacted';
   insert temleadobj;
   
  
    
   Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());       
       
   Test.StartTest();
    
   temleadobj.LastName='Testingafter update';
   CalloutExternal.pipelineConnect(temleadobj.Id);
   update temleadobj;
   Test.StopTest();
   
 }
}
this run the test class you can see your trigger and related class code covereage. 

hope this solve your issue. 

Thanks
karthik

 

All Answers

karthikeyan perumalkarthikeyan perumal
Hello,

kinldy find the Test class for your callout trigger, 

First you need to create mock Response generatore class since your using call out in your trigger. 

Mock reponse class: 
 
@isTest
global class MockHttpResponseGenerator implements HttpCalloutMock {
    // Implement this interface method
    global HTTPResponse respond(HTTPRequest req) {
         
        // Create a fake response
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'application/json');
        res.setBody('{"example":"test"}');
        res.setStatusCode(200);
        return res;
    }
}

after creating this class you need to create  test class for your trigge. 
 
@isTest
public class TestLeadUpdateListener
{
 public static testMethod void TestLeadUpdate()
 {
   Lead temleadobj= new lead();
   temleadobj.LastName='TestChecking';
   temleadobj.Company='Testing';
   temleadobj.Status='Open - Not Contacted';
   insert temleadobj;
   
  
    
   Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());       
       
   Test.StartTest();
    
   temleadobj.LastName='Testingafter update';
   CalloutExternal.pipelineConnect(temleadobj.Id);
   update temleadobj;
   Test.StopTest();
   
 }
}
this run the test class you can see your trigger and related class code covereage. 

hope this solve your issue. 

Thanks
karthik

 
This was selected as the best answer
Beltran BajaBeltran Baja
Wow! this is brilliant. You just helped me save time, this is my first time creating Apex Code/trigger and I never knew that you need to do Unit Test before you can deploy it, not to mention the confusing documentation provided.

Thank you very much sir, Cheers! 
Beltran BajaBeltran Baja
By the way should I include the Test Class in the Change Set? or just the Working Class?
karthikeyan perumalkarthikeyan perumal
you should include test class as well in change set..
Beltran BajaBeltran Baja
I just did, thank you very much ;-)
Lorenzo SchoovaertsLorenzo Schoovaerts
@isTest
public class TestAccountToAwsQueueTrigger {

    @isTest static void testUpdateAccount() {
     
        String name = 'NV De veloere portemonnee';
        String vat = 'ABC123';
        String cpyNum = 'ABC0123';
        String vatStreetNumSuffx = 'Teststraat 2 bus 7b';
        String vatZip = '1030';
        String vatCity ='Star City';
        String vatCountry = 'La Belgica Grande';
        Account source = new Account(Name = name,
                                     VAT_Number__c=vat,
                                     Company_Number__c = cpyNum,
                                     VAT_Street_Number_Suffix__c = vatStreetNumSuffx,
                                     VAT_Zip_Postal_Code__c = vatZip,
                                     VAT_City__c = vatCity,
                                     VAT_Country__c = vatCountry);


	Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator()); 
        Test.startTest();
        insert(source);
        source.VAT_Zip_Postal_Code__c = '2222';
        update(source);
        Test.stopTest();
    }
    
}


User-added image

 

Does anyone have any idea where I am going wrong here? Thanks guys. 

karthikeyan perumalkarthikeyan perumal
Hello, 

Use this code in Line  22
 
if (test.isRunningTest())
Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());

also share your MockHttpResponseGenerator class

it may help you

Thanks
karthik