Test class for Apex Trigger for update

4.1k views Asked by At

I am new in Apex Development. I want to write a TestClass for my Apex Trigger.

I am sharing my code with you:

trigger ClosedOpportunityTrigger on Opportunity (before update) {
    for(Opportunity o:Trigger.New) {
        if(o.Probability==100 && o.Invoiced__c == true)
        {            
            Attachment a = new Attachment();
            try {
                a = [Select Id, Name from Attachment where ParentId =:o.Id];
            }
            catch(Exception e) {
                a = null;
            }
            if (a == null)
                o.addError('Add an attachment before you close the Opportunity');
            }
        }
    }
2

There are 2 answers

3
Tim Willis On BEST ANSWER

Goodluck

public static void testmethod(){

opportunity opp = new opportunity()
//change whatever fields u need to make probability 100%
opp.stage = 'Closed Won';
opp.Invoiced__c == true;

try{

insert opp
}
catch(Exception e){

string errormessage = e.getMessage();

}
//now that u know how to do it, do a positive test where you also add an          
//attachment
//as a side note, your catch block will never fire, because you aren't     
//catching any exceptions you are just getting a null string
}
1
sahildcoder On

There are 2 things that need to be done :- 1. Create a record in 'Opportunity' object. Update it using code. 2. Create an attachment. Here is the link for your reference https://developer.salesforce.com/forums/?id=906F00000008yzKIAQ