+ Start a Discussion
LudivineLudivine 

Test Trigger Fire Approval on Opportunity

Dear all,

I have amended a trigger in my org.
Pb is when I validate it in production I got an error message.
I think this is because my trigger has 0% code coverage.
Could you tell me how to write the test trigger on this function that fires Approval on Opportunities?

Here is the trigger that I want to implement :

trigger fireApproval on Opportunity (after insert, after update){
if(runCheck.runOnce())    {
  for (Opportunity Oppty: Trigger.new){
        if(Oppty.StageName == 'Impact Action' && (trigger.isInsert || trigger.oldMap.get(Oppty.id).StageName != 'Impact Action') && 
                    ((Oppty.Business_Group__c == 'Australasia' && Oppty.Business_Unit__c=='Corrugated')&& 
                            (Oppty.Division__c== 'QLD' ||Oppty.Division__c== 'National' ||
                             Oppty.Division__c== 'NSW' ||
                            Oppty.Division__c== 'SA' ||
                             Oppty.Division__c== 'VIC/TAS'||
                            Oppty.Division__c== 'WA'))){           
                             //modfied 2010-07-05 by Lee Tsiamis - Velteo
            //This will auto submit for approval.
            Approval.ProcessSubmitRequest req1 = new Approval.ProcessSubmitRequest();
            req1.setComments('Submitting request for approval.');
            String accountID = Oppty.id;
            req1.setObjectId(accountID);

            // Submit the approval request for the account 
            Approval.ProcessResult result = Approval.process(req1);
            // Verify the result 
            System.assert(result.isSuccess());
            System.assertEquals('Pending', result.getInstanceStatus(), 'Instance Status'+result.getInstanceStatus());
        }
        
        /*
         // --------------------------------------------- //
        // added by Ludivine Dos REis- Amcor, 2013-06-19 //
        // --------------------------------------------- //
        else if(Oppty.StageName == 'Planned - market'  
        && trigger.oldMap.get(Oppty.id).StageName != 'Planned - market'  
        && Oppty.Business_Group__c == 'Amcor Flexibles Europe & Americas'
                            )
                            {         
    //This will auto submit for approval.
    
            Approval.ProcessSubmitRequest req1 = new Approval.ProcessSubmitRequest();
            req1.setComments('Submitting request for approval.');
            String accountID = Oppty.id;
            req1.setObjectId(accountID);

            // Submit the approval request for processing 
            Approval.ProcessResult result = Approval.process(req1);
            // Verify the result 
            System.assert(result.isSuccess());
            System.assertEquals('Pending', result.getInstanceStatus(), 'Instance Status'+result.getInstanceStatus());
        }     */        
                     
         // --------------------------------------------- //
        // added by Matt Watson - Salesforce, 2012-02-20 //
        // --------------------------------------------- //
        // triggers "AA Beverage" approval processes (x3)
        else if(Oppty.Business_Group__c == 'Australasia' && Oppty.Business_Unit__c== 'Beverage' && 
                        (
                        (Oppty.StageName == 'Planned Action' && (trigger.isInsert ||
                        trigger.oldMap.get(Oppty.id).StageName != 'Planned Action')) ||
                        (Oppty.StageName == 'Impact Action' && (trigger.isInsert ||
                        trigger.oldMap.get(Oppty.id).StageName != 'Impact Action')) 
                        )
                )
        {            
            //This will auto submit for approval.
            Approval.ProcessSubmitRequest req1 = new Approval.ProcessSubmitRequest();
            req1.setComments('Submitting request for approval.');
            String accountID = Oppty.id;
            req1.setObjectId(accountID);

            // Submit the approval request for the account 
            Approval.ProcessResult result = Approval.process(req1);
            // Verify the result 
            System.assert(result.isSuccess());
            System.assertEquals('Pending', result.getInstanceStatus(), 'Instance Status'+result.getInstanceStatus());
        }
        
        
          }
}
    }

Many thanks for your help.
bob_buzzardbob_buzzard
Have you tried to write the test yourself? If not, is there a reason why you are happy to write apex that will run on your production system but won't attempt a test class?
LudivineLudivine
I have a test class on runcheck method that covers only 19% of the code so I need help to get more.

public class runCheck {

private static boolean run = true;

 public static boolean runOnce(){
 if(run){
 run=false;
 return true;
 }
 else{return run;}
 }

 private static testmethod void testrunCheck(){
 System.assert(runCheck.runOnce(), 'Recursion check failed. Please review OSRUtil recursion logic');
 System.assert(!runCheck.runOnce(), 'Recursion check failed. Please review OSRUtil recursion logic');
 }
}


bob_buzzardbob_buzzard
That test class looks like its been copied from developerforce (e.g. https://developer.salesforce.com/page/New_Opportunity_Save_Behavior) - have you written any test code yourself for the trigger?
LudivineLudivine
no I didn't of course If I was so strong I didn't ask help here :)
bob_buzzardbob_buzzard
But you aren't asking for help - you're asking for us to write all of the test code for you for free, which is very different.  If you have a go and hit problems I'm happy to try to advise you where the problems are, but I'm not going to do you job for you I'm afraid.
LudivineLudivine
bob thank you , Initial question was : Could you tell me how to write the test trigger on this function that fires Approval on Opportunities?

So that I can begin the test class and maybe some tips to test the method.
So you don't want to help me?
bob_buzzardbob_buzzard
There's a difference between helping you and doing it for you.  I am genuinely amazed by how many people are happy to dabble in production code but don't want to put any effort into testing it.

I suggest you read up on writing test classes :

- writing a test class for a trigger: https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_qs_test.htm
- how to write good unit tests : https://developer.salesforce.com/page/How_to_Write_Good_Unit_Tests
Shashikant SharmaShashikant Sharma
As bob said would be difficult to provide you actuall test class for your code but may be this could help : It has steps for writing test class for a trigger. You need to create data to statisfy conditions in your trigger like Opportunity.Stage should be Impact Action

http://forceschool.blogspot.in/2011/06/testing-trigger-structure.html
LudivineLudivine
Excellent, thank you both for your help. I will write one test class and will let you know how I go!
Thanks again and Have a nice day both of you.
LudivineLudivine
Dear all,

Following your help, I have built a new test class to test my approval process.

Now The Execution Test pass but I only get 22% (4/18) of code coverage, however  Ithink I have checked in the test class every main points...

I am stuck here, can you tell me what  I should test as well?

I have cleaned up my trigger :
trigger fireApproval on Opportunity (after update,after insert){
if(runCheck.runOnce())    {
  for (Opportunity Oppty: Trigger.new){
        if(Oppty.StageName == 'Impact Action' && (trigger.isInsert || trigger.oldMap.get(Oppty.id).StageName != 'Impact Action') && 
                    (Oppty.Business_Group__c == 'Amcor Flexibles Europe & Americas' ||
                            ((Oppty.Business_Group__c == 'Amcor Tobacco Packaging')))){           
                             //modfied 2014-10-14 by Ludivine Dos Reis
            //This will auto submit for approval.
            Approval.ProcessSubmitRequest req1 = new Approval.ProcessSubmitRequest();
            req1.setComments('Submitting request for approval.');
            String accountID = Oppty.id;
            req1.setObjectId(accountID);

            // Submit the approval request for the account 
            Approval.ProcessResult result = Approval.process(req1);
            // Verify the result 
            System.assert(result.isSuccess());
            System.assertEquals('Pending', result.getInstanceStatus(), 'Instance Status'+result.getInstanceStatus());
        }
        
        
         // --------------------------------------------- //
        // added by Ludivine Dos REis- Amcor, 2013-06-19 //
        // price reduction process Approval-------------//
        
        else if(Oppty.StageName == 'Planned - market'   
               && trigger.oldMap.get(Oppty.id).StageName != 'Planned - market'
               && Oppty.Business_Group__c == 'Amcor Flexibles Europe & Americas'                    
                        ){       
                                                       
    //This will auto submit for approval.
            Approval.ProcessSubmitRequest req1 = new Approval.ProcessSubmitRequest();
            req1.setComments('Submitting request for approval.');
            String accountID = Oppty.id;
            req1.setObjectId(accountID);

            // Submit the approval request for the account 
            Approval.ProcessResult result = Approval.process(req1);
            // Verify the result 
            System.assert(result.isSuccess());
            System.assertEquals('Pending', result.getInstanceStatus(), 'Instance Status'+result.getInstanceStatus());
        }
               
          }
}
    }



And here is my test class with 22% code coverage :

//
// This class contains unit tests for validating all Triggers 
//
@isTest
private class TestFireApproval_Trigger {

    private static testMethod void triggersTestFireApproval(){
        Profile p = [select id from profile where name='Standard User'];
        User u = new User(alias = 'standt', email='standarduser4@testorg.com',emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='en_US',
        localesidkey='en_US', profileid = p.Id, timezonesidkey='America/Los_Angeles', username='TESTUSER23@testorg.com');
        System.runAs(u) {   
        
//--> Create a new Opportunity

        Opportunity Op = new Opportunity();
 // Fill in mandatory fields       
        Op.stageName ='Idea Action';
        Op.RecordTypeId='01220000000TuZ1AAK';
        Op.CurrencyIsoCode ='EUR';
        Op.Accountid ='00120000003XRRYAA4';//Amcor ltd.
        Op.Business_group__c = 'Amcor Flexibles Europe & Americas';
        Op.Business_Unit__c ='FAME and extrusion';
        Op.Division__c ='AF Cambe';
        Op.Manufacturing_plant__c ='Cambe';
        Op.Step_change__c ='N/A';
        Op.industry__c ='Capsules';
        Op.Segment__c='Capsules';
        Op.Sub_Segment__c ='Capsules';     
        Op.Type = 'Volume Change';
        Op.Detailed_Action_Type__c = 'New Amcor Product Innovation';
        Op.Action_Risk__c ='Low';
        Op.budgeted_Action__c ='No';
        Op.Value_Plus_Site_Review__c = 'No';
        Op.ongoing__c ='Yes';
        Op.Customer_Value__c ='No';
        Op.CloseDate = system.today();        
        Op.Unadj_Expected_Annual_Impact__c = 30000;
        Op.Expected_Implementation_Date__c = system.today();
        Op.Expected_Impact_Date__c = system.today();
        Op.Expected_PM_of_New_Volume__c =30;
        Op.Expected_Units_Annually__c =100000;
        Op.Unit_of_Measure__c ='MSI';
        Op.Expected_Sales_Revenue__c =500000;
        Op.name ='TestFireApproval1';
        
        try{
            insert Op;                                     
        } catch (System.DmlException e){
            System.debug('we caught a dml exception: ' + e.getDmlMessage(0));    
        }
 
 
        
//--> Select the record        
        Opportunity B1 = ([Select Id from Opportunity where Name='TestFireApproval1' limit 1]); 
            
                     
//-->Test auto Fire Approval at First Idea stage
runCheck.runOnce();            
        //1- This will auto submit for approval.
        Approval.ProcessSubmitRequest req = new Approval.ProcessSubmitRequest();
        req.setComments('Submitting request for approval.');
        req.setNextApproverIds(new Id[] {UserInfo.getUserId()});
        String opID = B1.Id;
            req.setObjectId(opID);

            // Submit the approval request for the account 
            Approval.ProcessResult result = Approval.process(req);
            // Verify the result 
            System.assert(result.isSuccess());
            System.assertEquals('Pending', result.getInstanceStatus(), 'Instance Status'+result.getInstanceStatus());
     
       //2- Approve the submitted request      
        // First, get the ID of the newly created item    
        List<Id> newWorkItemIds = result.getNewWorkitemIds();
        
        // Instantiate the new ProcessWorkitemRequest object and populate it         
        Approval.ProcessWorkitemRequest reqb = new Approval.ProcessWorkitemRequest();
        reqb.setComments('Approving request.');
        reqb.setAction('Approve');
        reqb.setNextApproverIds(new Id[] {UserInfo.getUserId()});
        
        // Use the ID from the newly created item to specify the item to be worked             
        reqb.setWorkitemId(newWorkItemIds.get(0));
        
        // Submit the request for approval              
        Approval.ProcessResult resultb =  Approval.process(reqb);
        
        // Verify the results             
        System.assert(resultb.isSuccess(), 'Result Status:'+resultb.isSuccess());
      
      
//--> Test auto Fire Approval At Planned Market Stage
    
     //update Oppty planned market.
        Op.stageName ='Planned - market';
      
      Update B1;
      runCheck.runOnce();          
            //1-This will auto submit for approval.
            Approval.ProcessSubmitRequest requ= new Approval.ProcessSubmitRequest();
            requ.setComments('Submitting request for approval.');
            requ.setNextApproverIds(new Id[] {UserInfo.getUserId()});
            String opIDs = B1.Id;
            requ.setObjectId(opIDs);

            // Submit the approval request for the account 
            Approval.ProcessResult results = Approval.process(requ);
            
            // Verify the result 
            System.assert(results.isSuccess());
            System.assertEquals('Pending', results.getInstanceStatus(), 'Instance Status'+results.getInstanceStatus());
      
       //2- Approve the submitted request      
        // First, get the ID of the newly created item    
        List<Id> newWorkItemIds1 = results.getNewWorkitemIds();
        
        // Instantiate the new ProcessWorkitemRequest object and populate it         
        Approval.ProcessWorkitemRequest reqc = new Approval.ProcessWorkitemRequest();
        reqc.setComments('Approving request.');
        reqc.setAction('Approve');
        reqc.setNextApproverIds(new Id[] {UserInfo.getUserId()});
        
        // Use the ID from the newly created item to specify the item to be worked             
        reqc.setWorkitemId(newWorkItemIds1.get(0));
        
        // Submit the request for approval              
        Approval.ProcessResult resultc =  Approval.process(reqc);
        
        // Verify the results             
        System.assert(resultc.isSuccess(), 'Result Status:'+resultc.isSuccess());
      
    
    
//--> update Oppty implement.
        Op.stageName ='Implemented Action';
        Op.Expected_Impact_Date__c = system.today();
        Op.Expected_Units_Annually__c = 100000;
        Op.Expected_Sales_Revenue__c = 300000;
        Op.Expected_PM_of_New_Volume__c = 12;      
        
         update B1;
               
//-->update Oppty impact + Approval      
        Op.stageName ='Impact Action';       
        op.Actual_Implementation_Date__c = system.today();
        Op.Actual_Impact_Date__c = system.today();
        Op.Actual_Units_Annually__c = 100000;
        Op.Unadjusted_Actual_Annual_Impact__c =30000;
        Op.Actual_Sales_Revenue__c = 300000;       
        
        update B1;
        
            //1-This will auto submit for approval.
            Approval.ProcessSubmitRequest reqt = new Approval.ProcessSubmitRequest();
            reqt.setComments('Submitting request for approval.');
            reqt.setNextApproverIds(new Id[] {UserInfo.getUserId()});
            String opID1 = B1.Id;
            reqt.setObjectId(opID1);

            // Submit the approval request for the account 
            Approval.ProcessResult resultt = Approval.process(reqt);
            // Verify the result 
            System.assert(resultt.isSuccess());
            System.assertEquals('Pending', resultt.getInstanceStatus(), 'Instance Status'+resultt.getInstanceStatus());
     
     
       //2- Approve the submitted request      

        // First, get the ID of the newly created item    
        List<Id> newWorkItemIds2 = resultt.getNewWorkitemIds();
        
        // Instantiate the new ProcessWorkitemRequest object and populate it         
        Approval.ProcessWorkitemRequest reqD = new Approval.ProcessWorkitemRequest();
        reqD.setComments('Approving request.');
        reqD.setAction('Approve');
        reqD.setNextApproverIds(new Id[] {UserInfo.getUserId()});
        
        // Use the ID from the newly created item to specify the item to be worked             
        reqD.setWorkitemId(newWorkItemIds2.get(0));
        
        // Submit the request for approval              
        Approval.ProcessResult resultD =  Approval.process(reqD);
        
        // Verify the results             
        System.assert(resultD.isSuccess(), 'Result Status:'+resultD.isSuccess());
              
    // end tests 
    }
}
}