+ Start a Discussion
stollmeyerastollmeyera 

Help with System.assert - test case & trigger

I wrote a trigger to prevent specific users from deleting tasks that they do not own.  It basically says that if you are part of Profile A, you will receive an error if you try to delete a task you are not assigned to.  The class has 100% coverage of the trigger, but because of the nature of my trigger it throws the aforementioned error and fails the class.  How would one use System.assert to tell the class that the error is good, thus passing the test?

 

Trigger:

trigger PreventDeleteRep on Task (Before delete) {

    for (Integer i = 0; i < Trigger.Old.size(); i++) {
        if (Trigger.Old[i].OwnerID != UserInfo.getUserId() && UserInfo.getProfileId() != '00e600000013e5e') {
               // Cannot delete this task
               Trigger.Old[i].addError('This task cannot be deleted because you are not assigned as the owner.  Please contact an administrator.');
        }
    }
}

 

 

Test Class:

@isTest
private class PreventDeleteTest{
    static testMethod void testPrventDelete(){
    
    //Setup the task record
    Task t1 = new Task(
        OwnerID = '00560000001N7DH',
        Subject = 'test',
        Type = 'Cold Call',
        Status = 'Not Started',
        Priority = 'Normal',
        WhoId = '00QP0000002OltT');
    insert t1;
    User admin = [Select Profileid from User where Name = 'Admin' limit 1];
    System.runAs(admin)
    
    {
    delete t1;
    }
        Task t2 = new Task(
        OwnerID = '00560000001N7DH',
        Subject = 'test',
        Type = 'Cold Call',
        Status = 'Not Started',
        Priority = 'Normal',
        WhoId = '00QP0000002OltT');
    insert t2;
    User rep = [Select Profileid from User where Name = 'Rep' limit 1];
    System.runAs(rep)
    
    {
    delete t2;
    }
    
        Task t3 = new Task(
        OwnerID = '00560000001N7DH',
        Subject = 'test',
        Type = 'Cold Call',
        Status = 'Not Started',
        Priority = 'Normal',
        WhoId = '00QP0000002OltT');
    insert t3;
    User associate = [Select Profileid from User where Name = 'Associate' limit 1];
    System.runAs(associate)
    {
    delete t3;
    }
  }
}

 

Best Answer chosen by Admin (Salesforce Developers) 
BritishBoyinDCBritishBoyinDC

In your test class, add a try / catch around the delete statement, and then do a system assert on the error message you get back...

 

Also, you need to remove those hard coded Ids - that's not going to work when you deploy to another system...create the WhoId as part of the test....

All Answers

LakshmanLakshman

The addError() method stops execution of code and roll backs current event(delete in your case) so that's why your trigger is failing.

Modify your trigger as below:

 

trigger PreventDeleteRep on Task (Before delete) {

    for (Integer i = 0; i < Trigger.Old.size(); i++) {
        if (Trigger.Old[i].OwnerID != UserInfo.getUserId() && UserInfo.getProfileId() != '00e600000013e5e') {
               // Cannot delete this task
               if (!Test.isRunningTest())
               Trigger.Old[i].addError('This task cannot be deleted because you are not assigned as the owner.  Please contact an administrator.');
        }
    }
}

 

This would help you get rid of the error but some code coverage % will be decreased.

 

Regards,

Lakshman



BritishBoyinDCBritishBoyinDC

In your test class, add a try / catch around the delete statement, and then do a system assert on the error message you get back...

 

Also, you need to remove those hard coded Ids - that's not going to work when you deploy to another system...create the WhoId as part of the test....

This was selected as the best answer
stollmeyerastollmeyera

Thanks for the help everyone.  I updated my trigger and test class with your suggestions as well as some other things i noticed, but the test is missing lines nine and ten which is the vital part of the trigger and is dropping the code coverage to 66%.  I know it has to do with the try/catch statement, which is a new concept to me (btw I have no background in computer science).  Any help is appreciated.

 

Trigger

trigger PreventTaskDeleteRepAssociate on Task (Before delete) {

    for (Integer i = 0; i < Trigger.Old.size(); i++) {
        if (Trigger.Old[i].OwnerID != UserInfo.getUserId() && 
        UserInfo.getProfileId() == '00e60000001BOaJ' || 
        UserInfo.getProfileId() == '00e60000001BOaE') 
        {
               // Cannot delete this task
               if (!Test.isRunningTest())
               Trigger.Old[i].addError('This task cannot be deleted because you are not assigned as the owner.  Please contact an administrator.');
        }
    }
}

  test class

@isTest
private class PreventDeleteTest2{
    static testMethod void testPrventDelete(){
    
    //Setup L1
    Lead l1 = new Lead(
        OwnerID = '00560000001N7DH',
        Status = 'New',
        Company = 'Test',
        LastName = 'Test',
        LeadSource = 'Advertising',
        Lead_Type__c = 'Inbound',
        Industry = 'Fitness');
    insert l1;
        
    //Setup the task record and associate with L1
    Task t1 = new Task(
        OwnerID = '00560000001N7DH',
        Subject = 'test',
        Type = 'Cold Call',
        Status = 'Not Started',
        Priority = 'Normal',
        WhoId = l1.id);
    insert t1;
    User admin = [Select Profileid from User where Name = 'Andy Stollmeyer' limit 1];
    System.runAs(admin)
    
    //Delete t1 as an Admin user
    {
    delete t1;
    }
    
    //Setup L2
    Lead l2 = new Lead(
        OwnerID = '00560000001N7DH',
        Status = 'New',
        Company = 'Test',
        LastName = 'Test',
        LeadSource = 'Advertising',
        Lead_Type__c = 'Inbound',
        Industry = 'Fitness');
    insert l2;
    
    //Setup t2 and relate to L2
        Task t2 = new Task(
        OwnerID = '00560000001N7DH',
        Subject = 'test',
        Type = 'Cold Call',
        Status = 'Not Started',
        Priority = 'Normal',
        WhoId = l2.id);
    insert t2;
    User rep = [Select Profileid from User where Name = 'ANDY TEST' limit 1];
    System.runAs(rep)
    
    //Delete t2 as a sales rep and assert the error message
    {try
    {
    delete t2;
    }
    catch (exception e) {
    
        System.assert(e.getMessage().equals('This task cannot be deleted because you are not assigned as the owner. Please contact an administrator.'));
        }
    }

  }
}

 

BritishBoyinDCBritishBoyinDC

I'm guessing it's because you still have this line in there:

if (!Test.isRunningTest())

 

A such, it will never add the error

 

remove that if statement, and it should work fine

LakshmanLakshman

Yes adding of try catch will be a better option in this case as the number of lines in your trigger are less.

Remove if (!Test.isRunningTest()) from trigger and the results would be as expected, 100% code coverage..... :)

stollmeyerastollmeyera

Thanks everyone, got it figured out.  The main problem was that the profileID was hardcoded, which was frowned upon in an earlier post.  I fixed this, removed the if statement and all is good.  Thanks for the help!!

stollmeyerastollmeyera

Unfortunately I have to rescind my previous post as I get the following error when I try to deply:

 

Failure Message: "System.AssertException: Assertion Failed", Failure Stack Trace: "Class.PreventDeleteTest2.testPrventDelete: line 63, column 9 External entry point"

 

This was something I was scared of as I not 100% sure how to use a try/catch statement.  I am researching now but figured it wouldnt hurt to post here for archival purposes

 

EDIT:Forgot to mention that line 63 is where i start to assert the error message, which is this line of code:

 

 System.assert(e.getMessage().equals('This task cannot be deleted because you are not assigned as the owner. Please contact an administrator.'));

 

stollmeyerastollmeyera

Fixed.  Changed the system assert to run off of the dml status code, which fixed the issue.  

 

        System.assertEquals('FIELD_CUSTOM_VALIDATION_EXCEPTION'  , 
        e.getDmlStatusCode(0));

 rather than referencing the actual error code:

 

      System.assert(e.getMessage().equals('This task cannot be deleted because you are not assigned as the owner.  Please contact an administrator or the record owner.'),
      e.GetMessage());

 

mayurguptamayurgupta
System.assert(e.getMessage().contains('This task cannot be deleted because you are not assigned as the owner.  Please contact an administrator or the record owner.'));

This will work... :)