Tuesday, 31 May 2011

Test Method for Trigger

Hi,

I just saw a problem on develoer community. I would like to share it with you.


Problem : I need help with the test method of this trigger, can someone please help me with the code, the trigger works but do not know how to create the test methods to deploy it to production:


The trigger is:
trigger CopyAttachments on MileStone__c(after insert)
{
Attachment[] attList = [select id, name, body from Attachment where ParentId = :Trigger.new[0].Opportunity__c];
Attachment[] insertAttList = new Attachment[]{};
 
         for(Attachment a: attList)
         {
               Attachment att = new Attachment(name = a.name, body = a.body, parentid = Trigger.new[0].id);
               insertAttList.add(att);
         }
       if(insertAttList.size() > 0)
       {
            insert insertAttList;
       }
Solution :
@isTest
private class TestCopyAttachments 
    { 
        //
        // This testMethod tests CopyAttachments triger
        // 
        public static testmethod void testCopyAttachments()
            {
                       
                //Insert a new instance of Oppurtunity Object with test values 
                Opportunity opr = new Opportunity(Name = 'Test' , StageName = 'TestStag' , CloseDate = Date.today());
                insert opr;
                
                //Insert a list of Oppurtunity Object with test values 
                List<Attachment> listAtt = new List<Attachment>();
                
                for(Integer i = 0; i < 5 ; i++)
                    { 
                        Attachment att = new Attachment(Name = 'TestAttachement', ParentId = opr.id , Body = Blob.valueOf('Test Attachment'));
                        listAtt.add(att);
                    }
                
                insert listAtt;
                
                test.startTest();
                
                MileStone__c mileStone = new MileStone__c(Opportunity__c = opr.id);
                insert mileStone;
                List<Attachment> listAttCopied = [Select id From Attachment where ParentId =: mileStone.id];
                system.assertEquals(listAttCopied.size() , listAtt.size());
                
                test.stopTest();
            }
    }

URL for issue in community

2 comments:

  1. This is a great blog! thank you very much!! I have created a trigger easily following your instructions, hope this blog will help me to start with apex code in an easy way!!:))

    ReplyDelete
  2. this blog is helpful for beginners...

    ReplyDelete

Tweet