+ Start a Discussion

Creating test class for Attachment Trigger


I am new to APEX and I created a trigger on Attachments. My goal is to set the Attachment to Private for a specific object and the file ends with .xls. It works perfectly fine but I am having creating test class for it and I can't deploy it to production. The code is below, can someone help me build a test class for it?
trigger SetAttachmentPrivate on Attachment (before insert) {
    string s;
    for(Attachment record:Trigger.new) {
        if((String.valueOf(record.parentId)).startswith('001') && (String.valueOf(record.Name)).endswith('.xls'))
            record.IsPrivate = TRUE;

Any assistance is greatly appreciated. Thanks
Balaji BondarBalaji Bondar
Hi ,

Please try code like below :
Account acc=new Account(Name='Acme Inc');
insert acc;		

Blob b = Blob.valueOf(‘Test Data’);
Attachment attachment = new Attachment();
attachment.ParentId = acc.ID;
attachment.Name = ‘TestAttachmentforParent.xls’;
attachment.Body = b;
Important :
If this is what you were looking for then please mark it as a "SOLUTION" or You can Click on the "Like" Button if this was beneficial for you.
Hi Bajaji,

Thank you for your help.

Actually, I have the same exact code you have right there but I'm only getting 75% code coverage. When I try to check with developer console, I'm getting with a red mark on "attach.IsPrivate = TRUE;".

Is there a possible way to create a code on that line?