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
Janaki RaoJanaki Rao 

How to write Test class for Contact Duplication Trigger

i am writing a test Class to detect duplicate based on 3 custom fields called User__c, Quater_Year__c,Month__c , i have written the bulkified code and invoked the class from a trigger, how do i cover 100%

Handler class
 
public class ContactTriggerHandler {

    public static void dupContactError (List <Contact> newTrigCon) {
        
            Id recordTypeId = Schema.SObjectType.Contact.getRecordTypeInfosByDeveloperName().get('Contact').getRecordTypeId();
        
    //List of all Contact Records currently in the database    
    List <Contact> allCon = [SELECT ID, Name, User__c, Quater_Year__c,RecordTypeId, Month__c FROM Contact where RecordTypeId=:recordTypeId];
        
        //Iterate through new potential records
        for (Contact oneConTrig : newTrigCon) {
            
            //Needed to iterate through all existing records which is contained in the allCon List
            for (Integer i = 0; i < allCon.size(); i++)
            
            //If all conditions are met, there is a duplicate and thus, returns an error.
            if (oneContrig.User__c == allCon[i].User__c 
                && oneContrig.Quater_Year__c == allCon[i].Quater_Year__c 
                && oneConTrig.Month__c == allCon[i].Month__c
                && oneConTrig.RecordTypeId == allCon[i].RecordTypeId) {

                    oneConTrig.addError('Duplicate Contact Error! This record already exists.');
 
           }
        }      
    }
}

Trigger
 
trigger ContactTrigger on Contact (before insert, before update) {

    ContactTriggerHandler.dupContactError(Trigger.new);
    
}

My Test class with 50% code coverage
 
@isTest
public class ContactTriggerHandlerTestClass {
    
    static testmethod void Duplication(){
        
        List<Contact> Contacts = new list <Contact>();
        Id RecordTypeIdLead = Schema.SObjectType.Contact.getRecordTypeInfosByName().get('Contact').getRecordTypeId();
        
        Account testAccount = new Account();
        testAccount.Name='DCCL' ;
        insert testAccount;
        
        contact con = new contact();
        con.FirstName='Julian';
        con.LastName='Rogers';
        con.Month__c = 'march';
        con.Quater_Year__c = '2020';
        con.AccountId = testAccount.id;
        con.Email = 'hello123@gmail.com';
        Contacts.add(con);
        insert con;
    }
    
}

​​​​​​​
Best Answer chosen by Janaki Rao
SarvaniSarvani
Hi Swetha,

Please place debug statements in your test class and see if the first contact is inserted like :

System.debug('Contact  inserted...and Id is .....'+con.id)

In your catch block add below line to check if its throwing error.
System.debug('Error message is '+ex.getMessage());

Also please change your line 40 in test class as it has space between the message:
Boolean expectedExceptionThrown =  ex.getMessage().contains('Duplicate Contact Error! This record already exists.') ? true : false;

Can you please paste your test class in case issue persists.

Thanks

All Answers

SarvaniSarvani
Hi Swetha,

There is no code in your test class which covers lines between line 17 to line 22. Please input User__c and recordtype fields in your contact details as you are comparing that fields also. I am not sure what is the datatype of your custom field user__c. I assumed its text field and gave the values. Plese change as per your datatype. 

Try below code:
 
@isTest
public class ContactTriggerHandlerTestClass {
    
    static testmethod void Duplication(){
        
        List<Contact> Contacts = new list <Contact>();
       Id RecordTypeIdContact
=schema.SObjectType.Contact.getRecordTypeInfosByName().get('Contact').getRecordTypeId(); 
//insert Account     
Account testAccount = new Account(); 
     testAccount.Name='DCCL' ; 
     insert testAccount;
// insert contact  
     contact con = new contact(); 
     con.FirstName='Julian'; 
     con.LastName='Rogers'; 
     con.Month__c = 'march'; 
     con.Quater_Year__c = '2020'; 
     con.AccountId = testAccount.id; 
     con.User__c= 'Test User';
     con.Email = 'hello123@gmail.com';
     con.recordtypeid=RecordTypeIdContact ;
     insert con;
       
// Trying to insert duplicate contact with same User__c, Month__c, Quater_Year__c  and recordtype as your are comparing these fields in your trigger.
        
      if(con.id!=NULL){
        contact con1=new contact();
        con1.firstname='Testing';
        con1.lastname='duplicate Contact';
        con1.Month__c = 'march';
        con1.Quater_Year__c = '2020';
        con1.AccountId = testAccount.id;
​​​​​​​        con1.User__c= 'Test User';
        con1.recordtypeid=RecordTypeIdContact ;
        try{
        insert con1;
        }
        catch(Exception ex){
            Boolean expectedExceptionThrown =  ex.getMessage().contains('Duplicate Contact Error! This record    already exists.') ? true : false;
            System.assertEquals(expectedExceptionThrown, true);
        }
        }
        
        
    }
    
}

Hope this helps ! Please mark as bets if it does

Thanks
Janaki RaoJanaki Rao
@Sarvani

Thanks for the Help, i made the changes  but still the code Coverage Shows only 50%

User-added image
SarvaniSarvani
Hi Swetha,

Please place debug statements in your test class and see if the first contact is inserted like :

System.debug('Contact  inserted...and Id is .....'+con.id)

In your catch block add below line to check if its throwing error.
System.debug('Error message is '+ex.getMessage());

Also please change your line 40 in test class as it has space between the message:
Boolean expectedExceptionThrown =  ex.getMessage().contains('Duplicate Contact Error! This record already exists.') ? true : false;

Can you please paste your test class in case issue persists.

Thanks
This was selected as the best answer
Janaki RaoJanaki Rao
@Sarvani
it worked, i removed the user__c field and put the debug logs as you said, and tested it and it worked, 
one question how do i define a user lookup field in test class??

User-added image
Janaki RaoJanaki Rao
@sarvani
it covers 100%