function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
sathish Tadikamalla 8sathish Tadikamalla 8 

Test class for TriggerHandler


Hi All,

Here by i'm adding my trigger & triggerHandler class that i have written. Can anybody give me TestClass for this?Urgent reply needed.
Trigger
_------------------
trigger CaseTrigger on Case (after undelete, before delete, before insert, after update) {

    CaseTriggerHandler handler = new CaseTriggerHandler();    

    //Delete related action plans
    if (trigger.isdelete ){
        handler.OnBeforeDelete(trigger.old);        
    }    
    //Undelete related action plans
    else if (trigger.isUnDelete ){
        handler.OnAfterUndelete(trigger.new);       
    }
    // deleting the cases if Delete_Case__c sets to true
    else if (trigger.isUpdate && trigger.isAfter){        
        handler.OnAfterUpdate(trigger.new);
    }
}

/*********************************************************************************
CaseTriggerHandler  class:
----------------------------------------------
public without sharing class CaseTriggerHandler {
     List<Case>          deleteCasesList     =     new list<case>();
     // constructor
     public CaseTriggerHandler(){}     
     // Call on after update trigger to delete all cases where Delete_Case__c is true
     public void OnAfterUpdate(List<Case> ListCase){         
         for( Case c : ListCase){
                 // if Delete case is true add this record to list
                 if(c.Delete_Case__c){
                    Case c1=new Case(Id=c.Id);
                    deleteCasesList.add(c1);
                 }
            }
            // deleting the list items 
            if(deleteCasesList != null && deleteCasesList.size()>0){            
                 delete deleteCasesList;
            }
     }
     // Call on Before Delete trigger on Case Object
     public void OnBeforeDelete(List<Case> ListCase){     
        set<ID>             cIds    = new set<ID>();
        List<String>        apIds   = new List<String>();
        List<ActionPlan__c> deletePermantently_apIds= new List<ActionPlan__c>();       
        for( Case c : ListCase ){
            cIds.add( c.Id );
        }
        
        /* GET Action Plans to delete from recycle bin */
        deletePermantently_apIds = [ select Id, Name , LastModifiedDate from ActionPlan__c where Case__c in : cIds and isDeleted = true ALL ROWS ];
        
        if ( deletePermantently_apIds.size() >0 ){          
            Database.emptyRecycleBin(deletePermantently_apIds);
        }           
        
        //Get all action plans associated with Campaigns
        for( Case a : [Select (Select Id From Action_Plans__r) From Case a where Id in : cIds]){
            if (a.Action_Plans__r.size() >0 ){
                for(ActionPlan__c ap :a.Action_Plans__r ){
                    apIds.add(ap.Id);
                }
            }
        }
        if ( apIds.size() >0 ){
            ActionPlansBatchDelete aPBatch = new ActionPlansBatchDelete(apIds, Userinfo.getUserId());
            Database.ExecuteBatch( aPBatch );       
        }
    }
    // Call on After Undelete trigger on Case Object
    public void OnAfterUndelete(List<Case> ListCase){    
        set<ID>             cIds    = new set<ID>();           
        for( Case c : ListCase){
            cIds.add( c.Id );
        }
        list <ActionPlan__c> aPs = [ select Id from ActionPlan__c where Case__c in : cIds ALL ROWS ];
        
        try{
            if(ActionPlanObjectTriggerTest.isTest){
                //throw dmlException
                insert new Contact();   
            }
            //undelete aPs;
            Database.undelete( aPs,false);
        } catch ( Dmlexception e ){
            for (Case c: ListCase){
                c.addError('You can not undelete an action plan whose related object is deleted.');
            }
        }
    }
    
}
Abhishek BansalAbhishek Bansal
Hi,

Please find your required test class below :
 
@isTest(SeeAllData=false)
public with sharing class caseTriggerTest{
    private static testMethod void testUpdateCaseMethod() {
        List<Case> caseList = new List<Case>();
        Case testCase;
        for(Integer i=0; i<5 ;i++){
        	testCase = new Case(Delete_Case__c = false);
        	caseList.add(testCase);
        }
        insert caseList;
        
        for(Case cas : caseList){
        	cas.Delete_Case__c = true;
        }
        
        Test.startTest();
        update caseList;
        Test.stopTest();
    }
    
    private static testMethod void testDeleteCaseMethod() {
        List<Case> caseList = new List<Case>();
        Case testCase;
        for(Integer i=0; i<5 ;i++){
        	testCase = new Case(Delete_Case__c = false);
        	caseList.add(testCase);
        }
        insert caseList;
        
        List<ActionPlan__c> listOfAcPlan = new List<ActionPlan__c >();
        ActionPlan__c actPlan;
        
        for(Integer i=0 ; i<5; i++){
        	actPlan = new ActionPlan__c(Case__c = caseList[i].id, isDeleted = true); 
        	listOfAcPlan.add(actPlan);
        }
        listOfAcPlan[0].isDeleted = false;
        insert listOfAcPlan;
        
        Test.startTest();
        delete caseList;
        Test.stopTest();
    }
    
    private static testMethod void testUnDeleteCaseMethod() {
        List<Case> caseList = new List<Case>();
        Case testCase;
        for(Integer i=0; i<5 ;i++){
        	testCase = new Case(Delete_Case__c = false);
        	caseList.add(testCase);
        }
        insert caseList;
        
        List<ActionPlan__c> listOfAcPlan = new List<ActionPlan__c >();
        ActionPlan__c actPlan;
        
        for(Integer i=0 ; i<5; i++){
        	actPlan = new ActionPlan__c(Case__c = caseList[i].id, isDeleted = true); 
        	listOfAcPlan.add(actPlan);
        }
        insert listOfAcPlan;
        
        delete caseList;
        
        Test.startTest();
        undelete caseList;
        Test.stopTest();
    }
    
}
Let me know if you have any issue in it.

Thanks,
Abhishek
 
Amit Chaudhary 8Amit Chaudhary 8
Please check below post for test class.
http://amitsalesforce.blogspot.in/search/label/Test%20Class
http://amitsalesforce.blogspot.in/2015/06/best-practice-for-test-classes-sample.html

You can try Test class. I did some minar change Abhishek class.
@isTest()
public class caseTriggerTest
{
    private static testMethod void testUpdateCaseMethod() 
	{
        List<Case> caseList = new List<Case>();
        Case testCase;
        for(Integer i=0; i<5 ;i++)
		{
        	testCase = new Case(Delete_Case__c = false);
        	caseList.add(testCase);
        }
        insert caseList;
        
        for(Case cas : caseList)
		{
        	cas.Delete_Case__c = true;
        }
        
        Test.startTest();
			try
			{
				update caseList;
			}Catch(Exception ee)
			{}	
        Test.stopTest();
    }
    
    private static testMethod void testDeleteCaseMethod() 
	{
        List<Case> caseList = new List<Case>();
        Case testCase;
        for(Integer i=0; i<5 ;i++){
        	testCase = new Case(Delete_Case__c = false);
        	caseList.add(testCase);
        }
        insert caseList;
        
        List<ActionPlan__c> listOfAcPlan = new List<ActionPlan__c >();
        ActionPlan__c actPlan;
        
        for(Integer i=0 ; i<5; i++){
        	actPlan = new ActionPlan__c(Case__c = caseList[i].id, isDeleted = true); 
        	listOfAcPlan.add(actPlan);
        }
        listOfAcPlan[0].isDeleted = false;
        insert listOfAcPlan;
        
        Test.startTest();
			try
			{
			delete caseList;
			}Catch(Exception ee)
			{}	
        Test.stopTest();
    }
    
    private static testMethod void testUnDeleteCaseMethod() 
	{
        List<Case> caseList = new List<Case>();
        Case testCase;
        for(Integer i=0; i<5 ;i++)
		{
        	testCase = new Case(Delete_Case__c = false);
        	caseList.add(testCase);
        }
        insert caseList;
        
        List<ActionPlan__c> listOfAcPlan = new List<ActionPlan__c >();
        ActionPlan__c actPlan;
        
        for(Integer i=0 ; i<5; i++)
		{
        	actPlan = new ActionPlan__c(Case__c = caseList[i].id, isDeleted = true); 
        	listOfAcPlan.add(actPlan);
        }
        insert listOfAcPlan;
        
        
        Test.startTest();
			try
			{
				delete caseList;
				undelete caseList;
			}Catch(Exception ee)
			{}	
        Test.stopTest();
    }
    
}
Please follow below salesforce Best Practice for Test Classes :-

1. Test class must start with @isTest annotation if class class version is more than 25
2. Test environment support @testVisible , @testSetUp as well
3. Unit test is to test particular piece of code working properly or not .
4. Unit test method takes no argument ,commit no data to database ,send no email ,flagged with testMethod keyword .
5. To deploy to production at-least 75% code coverage is required
6. System.debug statement are not counted as a part of apex code limit.
7. Test method and test classes are not counted as a part of code limit
9. We should not focus on the  percentage of code coverage ,we should make sure that every use case should covered including positive, negative,bulk and single record .
Single Action -To verify that the the single record produces the correct an expected result .
Bulk action -Any apex record trigger ,class or extension must be invoked for 1-200 records .
Positive behavior : Test every expected behavior occurs through every expected permutation , i,e user filled out every correctly data and not go past the limit .
Negative Testcase :-Not to add future date , Not to specify negative amount.
Restricted User :-Test whether a user with restricted access used in your code .10. Test class should be annotated with @isTest .
11 . @isTest annotation with test method  is equivalent to testMethod keyword .
12. Test method should static and no void return type .
13. Test class and method default access is private ,no matter to add access specifier .
14. classes with @isTest annotation can't be a interface or enum .
15. Test method code can't be invoked by non test request .
16. Stating with salesforce API 28.0 test method can not reside inside non test classes .
17. @Testvisible annotation to make visible private methods inside test classes.
18. Test method can not be used to test web-service call out . Please use call out mock .
19. You can't  send email from test method.
20.User, profile, organization, AsyncApexjob, Corntrigger, RecordType, ApexClass, ApexComponent ,ApexPage we can access without (seeAllData=true) .
21. SeeAllData=true will not work for API 23 version eailer .
22. Accessing static resource test records in test class e,g List<Account> accList=Test.loadData(Account,SobjectType,'ResourceName').
23. Create TestFactory class with @isTest annotation to exclude from organization code size limit .
24. @testSetup to create test records once in a method  and use in every test method in the test class .
25. We can run unit test by using Salesforce Standard UI,Force.com IDE ,Console ,API.
26. Maximum number of test classes run per 24 hour of period is  not grater of 500 or 10 multiplication of test classes of your organization.
27. As apex runs in system mode so the permission and record sharing are not taken into account . So we need to use system.runAs to enforce record sharing .
28. System.runAs will not enforce user permission or field level permission .
29. Every test to runAs count against the total number of DML issued in the process .


Please let us know if this post will help you

 
prispris
Hi can anyone help me in checking this test class for trigger and its handler : This is very urgent :(  thank you in advance 

trigger ccOrderTrigger on ccrz__E_Order__c (before insert, after insert, after update) {

    if(Trigger.isBefore) {

        if(Trigger.isInsert) {

            //PolicyTriggerHandler.beforeInsert(Trigger.new);
            cc_OrderTriggerHandler.beforeInsert(trigger.new);
        }
    }
    else if(Trigger.isAfter) {

        if(Trigger.isInsert) {
            //AccountTriggerHandler.afterInsert(Trigger.new);
            cc_OrderTriggerHandler.afterInsert(Trigger.new);
        }
    }
  
    if (Trigger.isBefore && Trigger.isInsert) {

        for (ccrz__E_Order__c o : Trigger.new){
            if(o.ccrz__EffectiveAccountId__C != null){
                o.ccrz__Account__c = o.ccrz__EffectiveAccountId__C;
            }
        }
    } 
}
====================================Handler ====================================================================
public class cc_OrderTriggerHandler {

    //all operations to be performed before an order is inserted
    public static void beforeInsert(List<ccrz__E_Order__c> newList) {
        
         /* Logic Added by Priyanka on 7/9/2020 - BEGIN */
        Cache.Partition partition = Cache.Session.getPartition('local.order');     
        String OldOrderId = '';
        set<String> PreviousOrderSequenceRecieved = new set<String>();
        //String PreviousOrderSequenceRecieved = '';
        PreviousOrderSequenceRecieved = (set<string>)partition.get('PreviousOrder');
        System.debug('PreviousOrderSequenceRecieved>>>>>>>>>>'+PreviousOrderSequenceRecieved);
        for(String OldOrd : PreviousOrderSequenceRecieved) 
        {
            OldOrderId += (OldOrderId==''?'':',')+OldOrd;
        }
        System.debug('OldOrderIdCommaSeparatedOrder>>>>>>>>>>'+OldOrderId);
        
         /* Logic Added by Priyanka on 7/9/2020 - END */
        
        Set<String> sapCustomerIds = new Set<String>();
        Map<String, ID> contactAddrMap = new Map<String, ID>();
        Map<String, ID> accountMap = new Map<String, ID>();

        for (ccrz__E_Order__c o : newList)
        {
            o.Ref_Order_Number__c = OldOrderId;
            sapCustomerIds.add(o.SAP_Ship_To__c);
        }
    
        for(ccrz__E_ContactAddr__c ca : [SELECT ccrz__ContactAddrId__c, ID 
            FROM ccrz__E_ContactAddr__c
            WHERE ccrz__ContactAddrId__c IN :sapCustomerIds])
        {
            contactAddrMap.put(ca.ccrz__ContactAddrId__c, ca.ID);          
        }

        for(Account acc : [SELECT SAP_Account_Number__c, ID 
            FROM Account
            WHERE SAP_Account_Number__c IN :sapCustomerIds])
        {
            accountMap.put(acc.SAP_Account_Number__c, acc.ID);          
        }

        for (ccrz__E_Order__c o : newList) {
        
            if (o.ccrz__Account__c == null && o.SAP_Sold_To__c != null ) {
                o.ccrz__Account__c = accountMap.get(o.SAP_Sold_To__c);
            }
            if (o.ccrz__ShipTo__c == null && o.SAP_Sold_To__c != null) {
                o.ccrz__ShipTo__c = contactAddrMap.get(o.SAP_Ship_To__c);   
            }
        }
    }

    //all operations to be performed after an order is inserted
    public static void afterInsert(List<ccrz__E_Order__c> newList) {
        
        //Validate Future limits.
        if (newList.size() > 50) {
            for (ccrz__E_Order__c o : newList) {
                o.addError('You cannot insert or update more than 50 Orders at a time.');
            }
            return;
        }

        //Validateion passed.
        for(ccrz__E_Order__c o : newList) {
          if(o.ccrz__OrderId__c == null){
            ccOrderRestService.intgrateOrderById(o.Id);
            }
        }
    }
    public static void Passer(){
        Integer i = 0;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
    }
}
=========================================test class =============================================================
@IsTest
private class CCOrderTest {

    @isTest static void testSetAccountAndShipToOnOrder() {
        Account testAccount = new Account(Name = 'TestOrderCompany', SAP_Account_Number__c ='123456', BillingCountry = 'GB');
        insert testAccount;
        
        ccrz__E_Order__c testOrder = new ccrz__E_Order__c(ccrz__Account__c =testAccount.Id, SAP_Created_Date__c = Date.today(), Order_Reason__c = 'OR', ccrz__BuyerCompanyName__c=testAccount.Name, 
               SAP_Ship_To__c=testAccount.SAP_Account_Number__c, Sales_Org__c='1000', ccrz__RequestDate__c=Date.today(),ccrz__OrderId__c='121212',
            SAP_Sold_To__c=testAccount.SAP_Account_Number__c, ccrz__ExtCarrier__c='TestCarrier', Created_By_SAP_User_ID__c='SAPUSR', Order_Reason_Description__c='New Order',
            ccrz__ShipAmount__c=1000, ccrz__PONumber__c='909909');      
    
        insert testOrder;
        
        ccrz__E_ContactAddr__c CA = new ccrz__E_ContactAddr__c(ccrz__FirstName__c ='test');
        insert CA;
        
        testAccount = [select Id, Name from Account where Id = :testAccount.Id];
            System.assertEquals(testAccount.Name, 'Test Account');  
        
        testOrder = [select Id, ccrz__Account__c, ccrz__ShipTo__c FROM ccrz__E_Order__c WHERE Id =: testOrder.Id];
        System.assertEquals(testOrder.ccrz__PONumber__c, '909909');
    }
    
  /* @isTest static void testOrderIdAndPriceOnItem() {
        Account testAccount1 = [SELECT Id, Name, SAP_Account_Number__c, Contact_Address__c FROM Account WHERE Name='TestOrderCompany' ];        
        ccrz__E_Order__c testOrder1 = [select Id, ccrz__Account__c, ccrz__ShipTo__c FROM ccrz__E_Order__c WHERE ccrz__PONumber__c = '909909'];
        ccrz__E_OrderItem__c orderItem1 = new ccrz__E_OrderItem__c(ccrz__ExtName__c='121212', ccrz__Quantity__c=5,ccrz__SubAmount__c=2000, ccrz__Order__c = testOrder1.id);
        insert orderITem1;
        
        Account testAccount2 = [SELECT Id, Name, SAP_Account_Number__c, Contact_Address__c FROM Account WHERE Name='TestOrderCompany' ];        
        ccrz__E_Order__c testOrder2 = [select Id, ccrz__Account__c, ccrz__ShipTo__c FROM ccrz__E_Order__c WHERE ccrz__PONumber__c = '909909'];
        ccrz__E_OrderItem__c orderItem2 = new ccrz__E_OrderItem__c(ccrz__ExtName__c='121213', ccrz__Quantity__c=0,ccrz__SubAmount__c=2000, ccrz__Order__c = testOrder2.id);
        insert orderItem2;
        
        orderItem1 = [SELECT ID, ccrz__Order__c, ccrz__Price__c from ccrz__E_OrderItem__c WHERE ccrz__ExtName__c='121212'];
        System.assertEquals(testOrder1.ID, orderItem1.ccrz__Order__c);
        System.assertEquals(400, orderItem1.ccrz__Price__c);
    }*/
}
Alina KondrashevaAlina Kondrasheva
Hi, i'm write apex Trigger, but I can't figure out how to create a test for it.
here is my code.
trigger UpdateNetTotalOnOffer on Quotation_Request__c (after update) {
  Set<Id> offerId = new Set<Id>();
  Map<Id,Quotation_Request__c> nMap = new Map<Id,Quotation_Request__c>();
  nMap =Trigger.newMap;  
  for(Offer_to_Quotation_Request__c ofQR:[
      Select Offer__c,Quotation_Request__c  
      from Offer_to_Quotation_Request__c
      where Quotation_Request__c in :nMap.keySet()
    ]){
    offerId.add(ofQR.Offer__c);
  }
//  System.debug(offerId);
List<Offer_to_Quotation_Request__c> qrToRollup = [
  select Offer__c,Quotation_Request__c,Quotation_Request__r.Cost__c
  from Offer_to_Quotation_Request__c
 
];
//System.debug(qrToRollup[0].Quotation_Request__r.Cost__c);
// Map<Id, Offer__c> offersMap = new Map<Id, Offer__c>();
// for (Offer_to_Quotation_Request__c a : qrToRollup) {
//   if (!offersMap.containsKey(a.Offer__c)){
//     offersMap.put(a.Offer__c, new Offer__c(Id = a.Offer__c));
//   }
//   Offer__c offer = offersMap.get(a.Offer__c);
//   offer.Net_Total__c += a.Quotation_Request__r.Cost__c ;
// }
// update offersMap.values();
List<Offer__c> offerToUpdate = new List<Offer__c>();
for(AggregateResult qrToRollup :[select offer__c, Sum(Quotation_Request__r.Net_Total__c) offerTotal from Offer_to_Quotation_Request__c where Offer__c in: offerId GROUP BY Offer__c ]){
  offerToUpdate.add(new Offer__c(Net_Total__c = (Decimal) qrToRollup.get('offerTotal'), Id = (Id) qrToRollup.get('Offer__c')));
}
update offerToUpdate;
}
please help write a test
Abhishek BansalAbhishek Bansal
Reach out to me at gmail - abhibansal2790@gmail.com or skype - abhishek.bansal2790