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
sammy cyborgsammy cyborg 

How to write the Test class for the Apex Trigger

trigger populateContactEmail on Case (before insert , before update){
    Set<Id> setConIds = new Set<Id>();

    for(Case  obj : trigger.new){
        if(obj.Secondary_Contact__c != null)
            setConIds.add(obj.Secondary_Contact__c);
    }

    Map<Id , Contact> mapCon = new Map<Id , Contact>([Select Id, Email from Contact where id in: setConIds]);
    for(Case obj : trigger.new)
    {
        if(obj.Secondary_Contact__c != null)
        {
            //Protecting against bad Ids
            if ( mapCon.containsKey(obj.Secondary_Contact__c)) {
                Contact c = mapCon.get(obj.Secondary_Contact__c);
                obj.Secondary_Contact_Email__c = c.Email;
            }
        }
    }
}

 
Best Answer chosen by sammy cyborg
Ajay K DubediAjay K Dubedi
Hi Sammy,

You can use the below Test class code.
 
@isTest
private class CaseTrigger_Test {
    
    @isTest static void caseTest(){
        Contact conObject = new Contact();
        conObject.LastName = 'Contact';
        conObject.Email = 'abc@xyz.com';
        Insert conObject;
        
        Case caseObject = new Case();
        caseObject.Status = 'New';
        caseObject.Origin = 'Phone';
        caseObject.Secondary_Contact__c = conObject.Id;
        Insert caseObject;
    }
}

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Ajay Dubedi
www.ajaydubedi.com

All Answers

Priya GovindasamyPriya Govindasamy
All you have to do is prepare a test data with contact record and case record with Secondary_Contact__c = contact's id. Once you insert case it will cover code coverage for trigger.
Ajay K DubediAjay K Dubedi
Hi Sammy,

You can use the below Test class code.
 
@isTest
private class CaseTrigger_Test {
    
    @isTest static void caseTest(){
        Contact conObject = new Contact();
        conObject.LastName = 'Contact';
        conObject.Email = 'abc@xyz.com';
        Insert conObject;
        
        Case caseObject = new Case();
        caseObject.Status = 'New';
        caseObject.Origin = 'Phone';
        caseObject.Secondary_Contact__c = conObject.Id;
        Insert caseObject;
    }
}

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Ajay Dubedi
www.ajaydubedi.com
This was selected as the best answer