I picked up this trigger code yesterday and it works perfectly:

trigger OpportunityAutoUpdate on Opportunity (before insert)
   // get the ids of all the accounts
     Set<Id> accIds=new Set<Id>();
   for (Opportunity opp : trigger.new)

   // retrieve the accounts and owners
  List<Account> accs=[select id, OwnerId from Account where id in :accIds];
  Map<Id, Account> accById=new Map<Id, Account>();

   // iterate the opportunities, updating the opportunity owner to the account owner
   for (Opportunity opp : trigger.new)
       // any logic about when to do this - i.e. only if the current owner matches a
       // particular id goes here
      if (null!=opp.AccountId)
       }  }

I can not get it into our production Org as we only have 73% coverage.

Any ideas for writing a test class to help get this in?

Update: I found a way to get it in, how do I change the code so it only works if the opportunity owner if a Picklist value is selected?


2 Answers 2

private class testforAccount 
static testMethod void unittest()    
              Account objAccount = new Account(Name = 'Test');
              insert objAccount;

              Opportunity objOpp = new Opportunity(Name='TestOppt', CloseDate=Date.today(), StageName='Open',  AccountId =objAccount.Id)
              insert objOpp;    } }

I would split out the first and last loops in your trigger into separate methods and write tests for those

  • one for the loop that builds the list of Ids given a list of SObjects,
  • one that takes a list of opportunities and a map of Id, Account and sets the owner Id, per your second loop.

Note: you can create the map accById like this

Map<Id, Account> accById = new Map<Id, Account>(accs);

thus eliminating the .putAll() call.

By the time you've done that, your trigger itself will be just four lines long, your unit test coverage will be a lot higher and and you will have some reusable code as a bonus.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.