0

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)
 {
     accIds.add(opp.AccountId);
 }

   // 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>();
  accById.putall(accs);

   // 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)
       {
          opp.OwnerId=accById.get(opp.AccountId).OwnerId;
       }  }
}

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?

3

2 Answers 2

0
    @isTest 
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;    } }
0

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.

1

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.