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
Rajat Bhatt 4Rajat Bhatt 4 

Test class for before delete trigger

Hi,
I am new to Salesforce and i facing problem in making a test class for this trigger.
Any help would be appreciated.
Thanks in advance

trigger PreventContactDeletion on Contact (before delete) {

    Id id1 = userinfo.getProfileId();
    
    String  profileName = [select name from profile where id=:id1].Name;   
        
    for(Contact con : Trigger.old)
    {
        if(profileName =='Sales' & con.Contact_Type__c=='Billing')
        {
            con.addError('Contact with type Billing cannot be deleted');
        }
    }

}
Khan AnasKhan Anas (Salesforce Developers) 
Hi Rajat,

Greetings to you!

Please try the below code, I have tested in my org and it is working fine. Kindly modify the code as per your requirement.
 
@isTest
public class Test_PreventContactDelete {
    
    static testMethod void testMethod1() {
        Profile prof = [SELECT Id FROM Profile WHERE Name = 'Sales'];
        
        Contact con = new Contact() ;
        con.FirstName = 'Khan';
        con.LastName = 'Anas';
        con.Contact_Type__c = 'Billing';
        INSERT con;
        
        try {
            DELETE con;
        }
        catch(Exception ee)
        {}
    }    
}

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas
AJAY KRISHNA RAJAY KRISHNA R
Hi,

When using addError() it usually creates trouble in the completion of test classes. But here is a solution which you can try.
First, create a  custom exception which will be thrown after the delete operation in your test class then assert the Message which is actually thrown by your trigger which helps you to pass the test. An example is given below please refer.
 
Apex Trigger :

trigger PreventContactDeletion on Contact (before delete) {

           
    for(Contact con : Trigger.old)
    {
        if(con.Email=='test@testing.com')
        {
            con.addError('Contact cannot be deleted');
        }
    }

}
 
My Custom Exception :

public class MyException extends Exception {
    public override string getMessage(){
        return 'An exception should have been thrown by the trigger but was not.';
    }
}
 
Test Class

@IsTest

public class PreventContactDeletionTest {
    
    public static testmethod void method1(){
        Contact con = new Contact();
        con.LastName  = 'Ajay';
        con.Email = 'test@testing.com';
        insert con;
        try{
            delete con;
            throw new MyException('An exception should have been thrown by the trigger but was not.');
        }
        catch(Exception e){
            Boolean expectedExceptionThrown =  e.getMessage().contains('Contact cannot be deleted') ? true : false;
            System.AssertEquals(expectedExceptionThrown, true);
        } 
        
    }
    
}

Thanks
Ajay Krishna R
 
Rajat Bhatt 4Rajat Bhatt 4
Hi Khan Anas,
Thanks for replying, i have a validation rule on contact object in which first name , last name and account is mandatory.
So when i am giving static value of account ex. con.AccountId ='18 digit id'; it is running  but the code coverage area is 5/6 i.e. 83%.
could u help in resolving this.
Thanks & Regards,
Rajat
AJAY KRISHNA RAJAY KRISHNA R
Hi Rajat,

I just saw your reply about making your code coverage please don't use static Account Id in test classes which may lead to future errors when pushing it to the production. Create a test account in test class and give that account id for your contact when inserting contact in the test class.

Thanks 
Ajay Krishna R
Khan AnasKhan Anas (Salesforce Developers) 
Hi Rajat,

Try this:
@isTest
public class Test_PreventContactDelete {
    
    static testMethod void testMethod1() {
        Profile prof = [SELECT Id FROM Profile WHERE Name = 'Sales'];
        
        Account acc = new Account();
        acc.Name = 'Test Account';
        INSERT acc;

        Contact con = new Contact() ;
        con.FirstName = 'Khan';
        con.LastName = 'Anas';
        con.AccountId = acc.Id;
        con.Contact_Type__c = 'Billing';
        INSERT con;
        
        try {
            DELETE con;
        }
        catch(Exception ee)
        {}
    }    
}

Regards,
Khan Anas