Salesforce Apex Test class for an Opportunity record delete Trigger

Use Case:
-Test Class coverage for the Opportunity Record delete trigger
-Test Class coverage to AddError
-Test Class coverage to Non System admin profile

Main Apex Trigger:

Not allowed to delete the opportunity records if its closed

trigger OpportunityDeleteTrigger on Opportunity ( before delete ) {
    String name = [SELECT Name FROM Profile WHERE Id =:UserInfo.getProfileId()].Name;
    
    if( name != 'System Administrator' ) {
        if( Trigger.isBefore ) {
            if( Trigger.isDelete ) {
                for( Opportunity objOpportunity : Trigger.old ) {
                    if( objOpportunity.IsClosed == true ) {
                        objOpportunity.addError( 'This opportunity cannot be deleted becase it has been closed.  Please contact Sales Operations.' );
                    }
                }
            }
        }
    }
}

https://gist.githubusercontent.com/sakthivelsfdc/f21c5ee54ffe369481f738dac37e72e1/raw/ad7bff405a0b4d7b1f7b2b01a56cd662776a3962/OpportunityDeleteTrigger.trigger

Test Class:

1. Create apex class with @isTest anotation.
2. Create a user record with non admin users
3. Use System.runAs to execute your test class as per the non admin profile
4. Create test opportunity record with appropriate StageName value as per the Closed Won field to make sure the IsClosed value as True
5. Delete the created opporutnity
6. Use system.assertEquals to verify the IsClosed value.

/**
 *
 * This Apex Test Class Created to cover the Opportunity Trigger
 *  - Created Test User with non system admin profile
 *  - Used Syste.runAs to execute the test user
 *  - Created Opportunity Record
 *  - Deleted Opporutnity
 *  - Check AddError validation as per the Trigger
 *
 * @author  Sakthivel Madesh
 * @date    Sep 25, 2019
 */
@isTest
public class OpportunityDeleteTriggerTestClass {
    
    static testMethod void createOppMethod() {
        
        try {            
                Test.startTest();            
                Profile prof = [SELECT Id FROM Profile WHERE Name = 'Standard User']; //get a profile Id
                User testUser = new User(Alias = 'TDemo', Email = 'sakthi@theblogreaders.com', EmailEncodingKey = 'ISO-8859-1', FirstName = 'Demo', LanguageLocaleKey = 'en_US', LastName = 'User', LocaleSidKey = 'en_US', ProfileId = prof.Id, TimeZoneSidKey = 'America/Denver', Username = 'demo.sakthi@theblogreaders.com'); 
                insert testUser;
                System.runAs(testUser) {
                    Opportunity createOpp = new Opportunity();
                    createOpp.Name='test opp';
                    createOpp.StageName='Closed Won';
                    createOpp.Probability = 95;
                    createOpp.CloseDate=system.today();
                    insert createOpp;
                    Delete createOpp;
                
                    //Apex Trigger addError Checking
                    Opportunity testResult = [SELECT Id, IsClosed FROM Opportunity WHERE Id =: createOpp.Id];
                    system.debug('testResult.IsClosed:::'+testResult.IsClosed);
                    system.assertEquals(true, testResult.IsClosed);
            	}
            Test.stopTest();
            
        } catch(Exception e) {
            system.debug('error::'+e);
        }
    }
}

https://gist.githubusercontent.com/sakthivelsfdc/5981ca172d1b74af53029a3c6493a1e4/raw/b7a4fde10c613332231c3c1c61256ae423f3bf1b/OpportunityDeleteTriggerTestClass.cls

Source to study about test class:

Get Started with Apex Unit Tests from Trailhead – https://trailhead.salesforce.com/en/content/learn/modules/apex_testing/apex_testing_intro

About Test Class from Apex Developer Guide- https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_qs_test.htm

Different types of methods for Test Class – https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_test.htm

Written by 

I am Sakthivel Madesh, a certified Salesforce Advanced Developer & Administrator working on Salesforce Technology since 2011. I am currently working in Techforce Services as Sr. Salesforce Developer. I have worked on multiple technologies Like PHP, Java, Salesforce, I am very passionate about Salesforce and to earn 15x Salesforce Certification. I love Trailhead for learning Salesforce Skill and Become a Trailhead 5x Ranger too. I Love to Learn & Share my Salesforce knowledge to Salesforce Learners/Beginner using My Blog and Salesforce Community.

Leave a Reply

Your email address will not be published. Required fields are marked *

*