trigger CheckOrderAttachmentTrigger on Opportunity (before insert, before update) {
    try { 
        Map<Id,Opportunity> opportunityAttachments = new Map<Id,Opportunity>(
            [SELECT Id,(SELECT Id FROM Attachments) FROM Opportunity WHERE Id IN :Trigger.new]          

        for(Opportunity opp:Trigger.new) {    
            if(opp.StageName=='Order' && // If it is changing to closed/won...
               (!opportunityAttachments.containsKey(opp.id) || // And the opportunity was not found (Insert)...                
                opportunityAttachments.get(opp.id).Attachments == null ||// Or the opportunity attachment list was null...               
                opportunityAttachments.get(opp.id).Attachments.size()==0)) { // Or the attachment list has no entries...                  
                    opp.StageName.addError('Please attach Order form in Notes & Attachment section before changing opportunity stage to Order.'); // So we prevent saving here.                   
    } catch(exception e) {
        System.assert(e.getMessage().contains('expected message'), 'message=' + e.getMessage());        

You Need to Write like this..

public class CheckOrderAttachmentTriggerTest
Static TestMethod void CheckOrderAttachment()
    Account acct = new Account(Name = 'Test Account');
    insert acct;

    Opportunity om = new Opportunity(Name = 'Name', AccountId = acct.Id, StageName = 'CLosed Won', CloseDate = System.today());
    insert om;

    System.assertEquals(om.name, 'Name');

    Attachment attach = new Attachment();     
    attach.Name = 'Unit Test Attachment';
    Blob bodyBlob = Blob.valueOf('Unit Test Attachment Body');
    attach.body = bodyBlob;
    attach.parentId = om.id;
    insert attach;  

    List<attachment> att1 = [select id, name from Attachment where parent.id =: om.id];
    System.assertEquals(1, att1.size());
  • SFDC Developer - Trigger.New does not show Id value and its important, because it will never get in the Trigger while execution.. – user4567570 Jun 13 '17 at 10:13
  • 1
    yes i know, question is how to write a test class for trigger, so i have give sample code here, i am not saying that this an exact answer to above trigger. – user44771 Jun 13 '17 at 10:17

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