0

I've created a test which is supposed to create an account, assign a value to a particular field and then test the deletion of the record but fail because of the field value assigned.

My test is failing with this error:

enter image description here

This is my test code - is the test failing because I'm trying to do something I've forbidden in the test script?

@isTest

private class PreventIBISAccountDeletionTest {

    @isTest static void TestIBISAccountDeletion() {
        //Test data setup
        //Create an account with data source set to IBIS & then try to delete it
        
        Account acct = new Account(Name='Trigger Test' , Data_Source__c='IBIS');
        insert acct;
        
        // Start test
        
        Test.startTest();
          
        Database.DeleteResult result = Database.delete(acct, false);
        
        Test.stopTest();
        
        // Verify 
        // In this case the deletion should have been stopped by the trigger,
        // so verify that we got back an error.
       
        System.assert(!result.isSuccess());
        System.assert(result.getErrors().size() > 0);
        System.assertEquals('Cannot delete account with source IBIS.',
                             result.getErrors()[0].getMessage());

        
    }
    
    
    
}

1 Answer 1

2

Generally, it is an extremely poor idea to validate copy within error messages, and this failing test is a great example why. Instead, you should simply verify whether you hit an error or not, to ensure the behavior of the validation. The copy is a completely unimportant implementation detail. So you can just remove this assertion altogether.

Please note that in general, it is good practice to add an explanatory message for each assertion in your tests. Something like:

system.assertEquals(false, result.isSuccess(),
    'Deletion should be prevented for this Data Source');
2
  • 2
    Putting the first bit in other words; the reason why your test was failing is because the error message you were expecting (first argument in system.assertEquals()) was different from the error message your validation rule was configured to return.
    – Derek F
    Feb 1 at 17:30
  • @DerekF Thank you so much, following your tip it was fairly straightforward to get everything working in both the sandbox and then the production org. Onwards and upwards!
    – JonnyM
    Feb 1 at 20:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.