I'm a newbie to Apex and can't say how much I appreciate this Board. I have a simple Trigger set up to update the Description fields on the Opportunity Object. I need to write a Test to cover the Trigger.
Here's the Trigger:
trigger updateFields on Opportunity (before insert,before update) {
for(Opportunity opp : Trigger.new){
if(opp.StageName=='Closed as Won'){
(opp.description= 'Assessment Completed!!') ;
}
if(opp.StageName=='Closed as Lost'){
opp.description= 'Opportunity Lost';
}
}
}
****Here's the Test I attempted to write (I'm looking for feedback on this: ****
@isTest
public class SampleTest {
public static testmethod void MyMethod(){
Test.startTest();
// TO DO: implement unit test
Account account = new Account (Name = 'testa');
insert account;
Opportunity[] opportunitys = new Opportunity[]{
new Opportunity (name = 'test1',
account = account,
stagename = 'Closed As Won',
closedate = system.today(),
new Opportunity (name = 'test2',
account = account,
stagename = 'Closed As Lost',
closedate = system.today()
};
update opportunitys;
Test.stopTest();
}
}
Thanks!
opportunitys
in this case; you want to be inserting them, since they're records that don't already exist in the database.public String OPP_STAGE_CLOSEDWON {get {return 'Closed as Won';}}
and refer to the strings in your code and testmethod via the getter as inif(opp.StageName==CONSTANTS.OPP_STAGE_CLOSEDWON)
This way, if the picklist values change, you only have to change one class in your code base and you ensure that there are no typos between code and testmethods. In your example, code usesas
and testmethod usesAs
for stage.