I'm trying to create a few triggers that prevent most of our org from deleting various items in our cases and opportunities (such as activities, case comments, etc.) I have been able to create the triggers for all of the ones I need, and the test classes for all have received 100% coverage, except for the one I have made for Attachments. I'm unsure as to what's so special about the Attachment object that's preventing me from getting the code coverage on this one as well, and it's preventing me from moving all these triggers to production. Here is the trigger I made to prevent the deletion of attachments:
trigger NoDeleteonAttachment on Attachment (before delete)
{
String ProfileId = UserInfo.getProfileId();
List<Profile> profiles=[select id from Profile where name='System Administrator' or name='Management'];
if (2!=profiles.size())
{
}
else
{
for (Attachment a : Trigger.old)
{
if ( (profileId!=profiles[0].id) || (profileId!=profiles[1].id) )
{
a.addError('You can\'t delete this record!');
}
}
}
}
This should prevent any user that doesn't have the profile of 'System Administrator' or 'Management' from deleting the Attachment. Below is my test class:
@isTest
private class NoDeleteonAttachmentTest
{
private static testmethod void NoDeleteonAttachmentTest()
{
User U = [select id from User where name='Sam Jones'];
Account Acct = new Account(Name = 'Test');
insert Acct;
contact cont = new contact(Accountid = Acct.id, LastName='Test');
insert cont;
Task a=new Task(Ownerid = U.id, Subject = 'Test', Whoid = cont.id, Whatid = Acct.id, Status = 'Pending', Priority = 'Low', Description = 'Test');
insert a;
Case b = new Case();
insert b;
a.WhoId = b.Id;
Attachment attachTest = new Attachment(Name='Test');
attachTest.body = Blob.valueOf('');
attachTest.ParentID = b.Id;
attachTest.OwnerID = U.Id;
insert attachTest;
delete attachTest;
}
}
When I run the test, I get the error, System.DmlException: Delete failed. First exception on row 0 with id 00Pg0000001CCfTEAW; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, You can delete this record!:[]
Sam Jones (the user used in this test) is a user without the access required to be able to delete the attachment. Thus, the test runs correctly, it can't complete because he doesn't have the access to do this. My coverage stays at 0% however.
In my other tests, I get an error similar to this, and end up getting 100% coverage. Does anyone know what the hiccup is with the attachment object? Thanks in advance!