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
Manjunath SC 18Manjunath SC 18 

How to write a test class for an apex trigger for leadconversion if Company Domain name already exists in the Existing accounts

Hey Guys

i have designed a trigger, when i create a lead it checks weather the custom field Company_Domain_Name__c already exists in the Existing accounts, if it exists,it will not create a lead, it creates contact which is associated to that existing accounts
How do i write test classes for this Trigger
 
trigger AutoConvertLeadAccount on Lead (after insert) {
    Set<String> LeadCompanyDomainNamec = new Set<String>();
    List<Lead> newLeads = new List<Lead>();
    
    // Get all the new leads
    for(Lead l : system.trigger.new){
        newLeads.add(l);
        LeadCompanyDomainNamec.add(l.Company_Domain_Name__c);
    }
    
    /* Make some maps of account and Company Domain */
    List<Account> AccountList = [select Id, Company_Domain_Name__c, OwnerId,Private__c from Account where Company_Domain_Name__c IN: LeadCompanyDomainNamec AND Private__c=true];
    system.debug('AccountList '+AccountList);
    Map<ID, String> peAccounts = new Map<ID, String>();
    Map<ID, ID> peAccountsOwner = new Map<ID, ID>();
    
    if(!AccountList.isEmpty()){
        // Generic map for preventing loss of ids
        for(Account a : AccountList){
            peAccounts.put(a.id, a.Company_Domain_Name__c);
            peAccountsOwner.put(a.id, a.OwnerId);
            system.debug('peAccounts '+peAccounts);
        }
        
        // We will need this to get the id from the email address
        Map<String, ID> peAccountsFlipped = new Map<String, ID>();
        for(ID i : peAccounts.keyset()){
            peAccountsFlipped.put(peAccounts.get(i), i);
            system.debug('peAccountsFlipped '+peAccountsFlipped);
        }
        
        /* System Conversion Requirements */
        leadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
        List<Database.LeadConvert> leadConverts = new List<Database.LeadConvert>();
        Database.LeadConvert lc = new Database.LeadConvert();
        
        /* Configuring Payload */    
        for (Lead nl : newleads) {
            
            // Check to see if account already exists
            if(!peAccounts.isEmpty()){
                if(peAccountsFlipped.get(nl.Company_Domain_Name__c)!=null){
                    lc = new Database.LeadConvert();
                    lc.setLeadId(nl.id);
                    lc.setOverwriteLeadSource(false);
                    lc.setConvertedStatus(convertStatus.MasterLabel);
                    lc.setAccountId(peAccountsFlipped.get(nl.Company_Domain_Name__c));
                    lc.setOwnerId(peAccountsOwner.get(peAccountsFlipped.get(nl.Company_Domain_Name__c)));
                    lc.setDoNotCreateOpportunity(true);
                    system.debug('lc '+lc);
                    leadConverts.add(lc);
                }    
            } 
            
            system.debug(leadConverts);
        }
        
        // Fire Payload
        if(!leadConverts.isEmpty()){
            Database.LeadConvertResult[] lcr = Database.convertLead(leadConverts);
            System.debug(LoggingLevel.INFO, lcr);
        }
    }
}


 
Best Answer chosen by Manjunath SC 18
PRAKASH JADA 13PRAKASH JADA 13
Hi,

You wrote all of your code in Trigger itself. It would be good if you use a trigger handler. Then for object you don't need to write multiple trigger for multiple events. You can use one trigger with multiple handlers.

Here is your code:

Trigger:
------------------
trigger AutoConvertLeadAccount on Lead (after insert) {
    
    // Before events
    if(Trigger.isBefore) {
        if(Trigger.isInsert) {
            
        }
        if(Trigger.isUpdate) {
            
        }
    }
    
    // After Events
    if(Trigger.isAfter) {
        if(Trigger.isInsert) {
            AutoConvertLeadAccHandler.onAfterSave(Trigger.New);
        }
        if(Trigger.isUpdate) {
            
        }
    }
}

Handler:
---------------------
public class AutoConvertLeadAccHandler {
    
    // Method to execute of After Insert of Leads
    public static void onAfterSave(List<Lead> leads) {
        
        Set<String> LeadCompanyDomainNamec     = new Set<String>();
        
        // Loop to iterate over the list of Leads
        for(Lead l : leads){
            LeadCompanyDomainNamec.add(l.Company_Domain_Name__c);
        }
        
        /* Make some maps of account and Company Domain */
        List<Account> AccountList = [select Id, Company_Domain_Name__c, OwnerId,Private__c from Account where Company_Domain_Name__c IN: LeadCompanyDomainNamec AND Private__c=true];
        system.debug('AccountList '+AccountList);
        Map<ID, String> peAccounts = new Map<ID, String>();
        Map<ID, ID> peAccountsOwner = new Map<ID, ID>();
        
        if(!AccountList.isEmpty()){
            // Generic map for preventing loss of ids
            for(Account a : AccountList){
                peAccounts.put(a.id, a.Company_Domain_Name__c);
                peAccountsOwner.put(a.id, a.OwnerId);
                system.debug('peAccounts '+peAccounts);
            }
            
            // We will need this to get the id from the email address
            Map<String, ID> peAccountsFlipped = new Map<String, ID>();
            for(ID i : peAccounts.keyset()){
                peAccountsFlipped.put(peAccounts.get(i), i);
                system.debug('peAccountsFlipped '+peAccountsFlipped);
            }
            
            /* System Conversion Requirements */
            leadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
            List<Database.LeadConvert> leadConverts = new List<Database.LeadConvert>();
            Database.LeadConvert lc = new Database.LeadConvert();
            
            /* Configuring Payload */    
            for (Lead nl : leads) {
                
                // Check to see if account already exists
                if(!peAccounts.isEmpty()){
                    if(peAccountsFlipped.get(nl.Company_Domain_Name__c)!=null){
                        lc = new Database.LeadConvert();
                        lc.setLeadId(nl.id);
                        lc.setOverwriteLeadSource(false);
                        lc.setConvertedStatus(convertStatus.MasterLabel);
                        lc.setAccountId(peAccountsFlipped.get(nl.Company_Domain_Name__c));
                        lc.setOwnerId(peAccountsOwner.get(peAccountsFlipped.get(nl.Company_Domain_Name__c)));
                        lc.setDoNotCreateOpportunity(true);
                        system.debug('lc '+lc);
                        leadConverts.add(lc);
                    }    
                } 
                
                system.debug(leadConverts);
            }
            
            // Fire Payload
            if(!leadConverts.isEmpty()){
                Database.LeadConvertResult[] lcr = Database.convertLead(leadConverts);
                System.debug(LoggingLevel.INFO, lcr);
            }
        }
    }
    
}



Now the test class you need:

Test class with 100% code coverage:
----------------------------------------------------

@isTest
public class AutoConvertLeadAccHandlerTest {
    @testSetup static void prepareTestData() {
        Account account = new Account();
        account.Name                     = 'Test Account';
        account.Company_Domain_Name__c     = 'Test Company';
        account.Private__c                = true;
        
        insert account;
        
        List<Lead> leads                 = new List<Lead> ();
        Lead lead                         = new Lead(
            FirstName                     = 'Test A',
            LastName                    = 'Test A',
            Company                     = 'Test Company',
            Company_Domain_Name__c         = 'Lead Company');
        
        leads.add(lead);
        
        Lead lead1                         = new Lead(
            FirstName                     = 'Test B',
            LastName                    = 'Test B',
            Company                     = 'Test Company',
            Company_Domain_Name__c         = 'Test Company');
        
        leads.add(lead1);
        
        insert leads;
        
    }
    
    @isTest static void testNegative() {
        Lead lead = [Select Id, FirstName, Company_Domain_Name__c from Lead Where FirstName = 'Test A' LIMIT 1];
        System.assert(lead != null);
        System.assertEquals(lead.FirstName, 'Test A');
        System.assertNotEquals(lead.Company_Domain_Name__c, 'Test Company');
    }
    
    @isTest static void testPositive() {
        Lead lead = [Select Id, FirstName, Company_Domain_Name__c from Lead Where FirstName = 'Test B' LIMIT 1];
        System.assert(lead != null);
        System.assertEquals(lead.FirstName, 'Test B');
        System.assertNotEquals(lead.Company_Domain_Name__c, 'Lead Company');
    }
}