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
Andrew marshal 3Andrew marshal 3 

Create test class for this

Please create a test class for this 

public with sharing class LeadProcessor {
    
    public static void updateLeadStatus(List<Lead> leadsToUpdate) {
        Set<Id> accountIds = new Set<Id>();
        
        // Loop through the leads and collect the Account Ids
        for (Lead lead : leadsToUpdate) {
            accountIds.add(lead.AccountId);
        }
        
        // Query the related Accounts to check for duplicate leads
        List<Account> relatedAccounts = [SELECT Id, (SELECT Id, Email FROM Leads) FROM Account WHERE Id IN :accountIds];
        
        Map<String, Set<String>> emailToLeadIds = new Map<String, Set<String>>();
        
        // Loop through the related Accounts and Leads and create a map of Email to Lead Ids
        for (Account account : relatedAccounts) {
            for (Lead lead : account.Leads) {
                if (lead.Email != null) {
                    String emailKey = lead.Email.toLowerCase();
                    
                    if (emailToLeadIds.containsKey(emailKey)) {
                        emailToLeadIds.get(emailKey).add(lead.Id);
                    } else {
                        Set<String> leadIds = new Set<String>{lead.Id};
                        emailToLeadIds.put(emailKey, leadIds);
                    }
                }
            }
        }
        
        // Loop through the leads and check for duplicates based on Email
        for (Lead lead : leadsToUpdate) {
            if (lead.Email != null) {
                String emailKey = lead.Email.toLowerCase();
                
                if (emailToLeadIds.containsKey(emailKey) && !emailToLeadIds.get(emailKey).contains(lead.Id)) {
                    lead.addError('This Lead has the same email address as another Lead in the related Account.');
                } else {
                    if (lead.Status == 'New') {
                        lead.Status = 'Open';
                    }
                }
            }
        }
        
        update leadsToUpdate;
    }
    
}
Best Answer chosen by Andrew marshal 3
Abdul KhatriAbdul Khatri
Hi Andrew,

One question for my knowledge, if you can help me with that?
  • Where did you get the AccountId (Looks like a Standard field as there is no __c), I know the ConvertedAccountId field but never came across that field.
  • Is your code really working?
Also I placed some safety checks (null pointer checks) so your code doesn't crash in certain scenarios.
 
public with sharing class LeadProcessor2 {
    
    public static void updateLeadStatus(List<Lead> leadsToUpdate) {
        Set<Id> accountIds = new Set<Id>();
        
        // Loop through the leads and collect the Account Ids
        for (Lead lead : leadsToUpdate) {
            if(String.isNotBlank(lead.AccountId))
            	accountIds.add(lead.AccountId);
        }
        
        // Query the related Accounts to check for duplicate leads
        if(accountIds != null && !accountIds.isEmpty())
        	List<Account> relatedAccounts = [SELECT Id, (SELECT Id, Email FROM Leads) FROM Account WHERE Id IN :accountIds];
        
        Map<String, Set<String>> emailToLeadIds = new Map<String, Set<String>>();
        
        // Loop through the related Accounts and Leads and create a map of Email to Lead Ids
        for (Account account : relatedAccounts) {
            for (Lead lead : account.Leads) {
                if (lead.Email != null) {
                    String emailKey = lead.Email.toLowerCase();
                    
                    if (emailToLeadIds.containsKey(emailKey)) {
                        emailToLeadIds.get(emailKey).add(lead.Id);
                    } else {
                        Set<String> leadIds = new Set<String>{lead.Id};
                        emailToLeadIds.put(emailKey, leadIds);
                    }
                }
            }
        }
        
        // Loop through the leads and check for duplicates based on Email
        for (Lead lead : leadsToUpdate) {
            if (lead.Email != null) {
                String emailKey = lead.Email.toLowerCase();
                
                if (emailToLeadIds!= null && emailToLeadIds.containsKey(emailKey) 
                    	&& emailToLeadIds.get(emailKey) != null && !emailToLeadIds.get(emailKey).contains(lead.Id)) {
                    lead.addError('This Lead has the same email address as another Lead in the related Account.');
                } else {
                    if (lead.Status == 'New') {
                        lead.Status = 'Open';
                    }
                }
            }
        }
        
        update leadsToUpdate;
    }  
}

Regards,
Abdul Aziz Khatri

All Answers

SubratSubrat (Salesforce Developers) 
Hello Andrew ,

Please check with below and let me know further ;
 
@isTest
private class LeadProcessorTest {
    @isTest
    static void testUpdateLeadStatus() {
        // Create test data
        Account account = new Account(Name = 'Test Account');
        insert account;
        Lead lead1 = new Lead(FirstName = 'Test', LastName = 'Lead 1', Email = 'test1@example.com', AccountId = account.Id);
        insert lead1;
        Lead lead2 = new Lead(FirstName = 'Test', LastName = 'Lead 2', Email = 'test2@example.com', AccountId = account.Id);
        insert lead2;
        
        // Call the method being tested
        List<Lead> leadsToUpdate = new List<Lead>{lead1, lead2};
        LeadProcessor.updateLeadStatus(leadsToUpdate);
        
        // Check that the Status field was updated correctly
        lead1 = [SELECT Status FROM Lead WHERE Id = :lead1.Id];
        System.assertEquals('Open', lead1.Status);
        lead2 = [SELECT Status FROM Lead WHERE Id = :lead2.Id];
        System.assertEquals('Open', lead2.Status);
        
        // Create a duplicate Lead and verify that an error is thrown
        Lead lead3 = new Lead(FirstName = 'Test', LastName = 'Lead 3', Email = 'test1@example.com', AccountId = account.Id);
        insert lead3;
        leadsToUpdate = new List<Lead>{lead3};
        Test.startTest();
        try {
            LeadProcessor.updateLeadStatus(leadsToUpdate);
            System.assert(false, 'Expected a DmlException to be thrown.');
        } catch (DmlException e) {
            System.assert(e.getMessage().contains('This Lead has the same email address as another Lead in the related Account.'));
        }
        Test.stopTest();
    }
}

Hope the above test class works !
Thank you.​​​​​​​
Abdul KhatriAbdul Khatri
Hi Andrew,

One question for my knowledge, if you can help me with that?
  • Where did you get the AccountId (Looks like a Standard field as there is no __c), I know the ConvertedAccountId field but never came across that field.
  • Is your code really working?
Also I placed some safety checks (null pointer checks) so your code doesn't crash in certain scenarios.
 
public with sharing class LeadProcessor2 {
    
    public static void updateLeadStatus(List<Lead> leadsToUpdate) {
        Set<Id> accountIds = new Set<Id>();
        
        // Loop through the leads and collect the Account Ids
        for (Lead lead : leadsToUpdate) {
            if(String.isNotBlank(lead.AccountId))
            	accountIds.add(lead.AccountId);
        }
        
        // Query the related Accounts to check for duplicate leads
        if(accountIds != null && !accountIds.isEmpty())
        	List<Account> relatedAccounts = [SELECT Id, (SELECT Id, Email FROM Leads) FROM Account WHERE Id IN :accountIds];
        
        Map<String, Set<String>> emailToLeadIds = new Map<String, Set<String>>();
        
        // Loop through the related Accounts and Leads and create a map of Email to Lead Ids
        for (Account account : relatedAccounts) {
            for (Lead lead : account.Leads) {
                if (lead.Email != null) {
                    String emailKey = lead.Email.toLowerCase();
                    
                    if (emailToLeadIds.containsKey(emailKey)) {
                        emailToLeadIds.get(emailKey).add(lead.Id);
                    } else {
                        Set<String> leadIds = new Set<String>{lead.Id};
                        emailToLeadIds.put(emailKey, leadIds);
                    }
                }
            }
        }
        
        // Loop through the leads and check for duplicates based on Email
        for (Lead lead : leadsToUpdate) {
            if (lead.Email != null) {
                String emailKey = lead.Email.toLowerCase();
                
                if (emailToLeadIds!= null && emailToLeadIds.containsKey(emailKey) 
                    	&& emailToLeadIds.get(emailKey) != null && !emailToLeadIds.get(emailKey).contains(lead.Id)) {
                    lead.addError('This Lead has the same email address as another Lead in the related Account.');
                } else {
                    if (lead.Status == 'New') {
                        lead.Status = 'Open';
                    }
                }
            }
        }
        
        update leadsToUpdate;
    }  
}

Regards,
Abdul Aziz Khatri
This was selected as the best answer
Prateek Prasoon 25Prateek Prasoon 25
@isTest
private class LeadProcessorTest {
    
    @isTest
    static void testUpdateLeadStatus() {
        // Create test accounts
        List<Account> testAccounts = new List<Account>();
        testAccounts.add(new Account(Name='Test Account 1'));
        testAccounts.add(new Account(Name='Test Account 2'));
        insert testAccounts;
        
        // Create test leads
        List<Lead> testLeads = new List<Lead>();
        testLeads.add(new Lead(FirstName='Test', LastName='Lead 1', Email='test1@example.com', AccountId=testAccounts[0].Id, Status='New'));
        testLeads.add(new Lead(FirstName='Test', LastName='Lead 2', Email='test2@example.com', AccountId=testAccounts[1].Id, Status='New'));
        testLeads.add(new Lead(FirstName='Test', LastName='Lead 3', Email='test1@example.com', AccountId=testAccounts[0].Id, Status='New'));
        insert testLeads;
        
        // Call the method to update lead statuses
        LeadProcessor.updateLeadStatus(testLeads);
        
        // Verify that the leads were updated correctly
        testLeads = [SELECT Id, Status FROM Lead WHERE Id IN :testLeads];
        System.assertEquals('Open', testLeads[0].Status);
        System.assertEquals('Open', testLeads[1].Status);
        System.assertEquals(null, testLeads[2].Status);
        
        // Verify that the duplicate lead has an error message
        System.assert(testLeads[2].HasErrors());
    }
    
}

If you find this answer helpful, Please mark it as the best answer.