function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
matt.bylermatt.byler 

Test Methods for a Trigger

I have the following trigger that needs to have a test method before I can deploy it and would like any advice on how to do this.

 

 

trigger createworkorder on Opportunity (after update)
{
if(trigger.new[0].StageName=='closed won'&&(trigger.old[0].StageName<>'closed won'))
{
Work_Order__c obj=new Work_Order__c(Opportunity__c=trigger.new[0].id);
insert obj;
case c1=new case(Status='new',Subject='Create Product Cases for Work Order',Work_Order__c=obj.id);
insert c1;
}
}

Best Answer chosen by Admin (Salesforce Developers) 
sfcksfck

You will need to write some code that performs an update on an Opportunity (so as to fire the trigger) and then check that the case and the work order have been created and inserted.

 

For example, to test that the work order has been created you could check that one exists in the database:

 

(This is a sketch to start you off)

 

Opportunity opp = new Opportunity();
insert opp;
update opp; // this should fire the trigger
// Now check that the work order has been created
system.assertEquals(1, [select count() from work_order__c where opportunity__c = :opp.id]);

 

All Answers

Alok_NagarroAlok_Nagarro

Hi,

 

Try the following test method -

 

public static testMethod void testCreateWorkOrder

{

 // create opportunity with stage name = closed won

Opportunity op=new Opportunity(name='MyOpprtunity',StageName='Prospecting');

insert op;

 

// update the opportunity in order to test your trigger

op.StageName='Closed Won';

update op;

}

sfcksfck

You will need to write some code that performs an update on an Opportunity (so as to fire the trigger) and then check that the case and the work order have been created and inserted.

 

For example, to test that the work order has been created you could check that one exists in the database:

 

(This is a sketch to start you off)

 

Opportunity opp = new Opportunity();
insert opp;
update opp; // this should fire the trigger
// Now check that the work order has been created
system.assertEquals(1, [select count() from work_order__c where opportunity__c = :opp.id]);

 

This was selected as the best answer
matt.bylermatt.byler

Thanks so much guys it was a great help!!