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
Naveen Velkur 6Naveen Velkur 6 

How to write test class for the below trigger with 75% code coverage

trigger BlockCaseDeletion on Case (before delete) {
for (Case c : Trigger.old) {
        // Prevent deletion of cases
        c.addError('Cases cannot be deleted.');
    }
}
Mudit SharmaMudit Sharma
Hi Naveen , 
Please try this code
@isTest
public class TestBlockCaseDeletionTrigger {
    @isTest
    static void testBlockCaseDeletion() {
        // Create test cases
        List<Case> testCases = new List<Case>();
        for (Integer i = 0; i < 100; i++) { // Create 100 test cases
            Case c = new Case(Subject = 'Test Case ' + i, Description = 'Test Description ' + i);
            testCases.add(c);
        }
        insert testCases;
        // Try to delete test cases
        Test.startTest();
        try {
            delete testCases;
            // The above delete statement should trigger the validation rule
            // and prevent cases from being deleted.
        } catch (DmlException e) {
            // Check that the expected error message is present in the DmlException
            System.assertEquals('Cases cannot be deleted.', e.getDmlMessage(0));
        }
        Test.stopTest();
    }
}
 
SubratSubrat (Salesforce Developers) 
Hello naveen ,

To achieve at least 75% code coverage for the given trigger, you need to write a test class that covers the trigger's functionality. Here's a sample test class to provide the required coverage:

Trigger:
trigger BlockCaseDeletion on Case (before delete) {
    for (Case c : Trigger.old) {
        // Prevent deletion of cases
        c.addError('Cases cannot be deleted.');
    }
}
Test Class:
@isTest
public class Test_BlockCaseDeletion {
    @isTest
    static void testBlockCaseDeletion() {
        // Create test cases
        List<Case> casesToDelete = new List<Case>();
        for (Integer i = 0; i < 5; i++) {
            casesToDelete.add(new Case(Subject = 'Test Case ' + i));
        }
        insert casesToDelete;

        Test.startTest();
        // Try to delete the cases
        try {
            delete casesToDelete;
            // If the trigger works correctly, this line should not be reached
            System.assert(false, 'Deletion should be blocked by the trigger');
        } catch (DmlException e) {
            // Check if the error message is as expected
            System.assertEquals('Cases cannot be deleted.', e.getDmlMessage(0));
        }
        Test.stopTest();
    }
}


If this helps , please mark this as Best Answer.
Thank you.