+ Start a Discussion

Test class for a trigger

Hi All


Can you please help me in writing a test class for the following trigger. The scenario is whenever an opportunity is closed won or dead/lost a field should be updated in Case object.


trigger CaseUpadate on Opportunity (after update)
List <Case> caseList;
List <Id> oppIdList = new List <Id>();
for(Integer i=0; i<Trigger.new.size(); i++)
    if (Trigger.new[i].StageName != Trigger.old[i].StageName && (Trigger.new[i].StageName == 'Closed Won' || Trigger.new[i].StageName == 'Closed - Dead/Lost'))
caseList = [select Id, Opportunity_closed_won__c from Case where Opportunity__c in :oppIdList];
if (caseList.size() > 0)
    for(Case c : caseList)
        if (c.Opportunity_closed_won__c != true)
            c.Opportunity_closed_won__c = true;   
    update caseList;



private class TestTrigger {

    Opportunity o = new Opportunity (Name = 'Test', CloseDate=System.Today(), StageName = 'test');
    //add whatever other fields are required to save opportunity
    insert o;
     Case c = new Case (// add whatever fields are required to save it);
     insert c;

     o.stagename = 'Closed Won';
     update o;