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
MohiniMohini 

Need help with test class for the below trigger and apex handler. Please help me as I am stuck

.Scenrio : Trigger rolls up child revenue and cost record as average for similar product type and sum for different product type:.
Please helo me write a test class for this 

Trigger :trigger RollupSubAmt  on Sub_Opportunity__c (after insert, after update,after delete,after undelete) {
     Set<Id> oppIdSet = new Set<Id>();
    Map<Id, List<AggregateResult>> revenuecostAmountMap = new Map<Id, List<AggregateResult>>();
    //Map<Id, Double> costTypeMap = new  Map<Id, Double>();
     List<Opportunity> opptyListToUpdate = new List<Opportunity>();
     if(Trigger.isInsert || Trigger.isUpdate || Trigger.isUndelete){
          for(Sub_Opportunity__c subopp : Trigger.new){
             if(subopp.Opportunity__c != null){
                oppIdSet.add(subopp.Opportunity__c);
             }      
          }
         RollupSubAmtHandler.afterOperation(oppIdSet);
     }
    
     If(Trigger.isDelete){
       for(Sub_Opportunity__c opp : Trigger.old){
            if(opp.Opportunity__c!= null){
               oppIdSet.add(opp.Opportunity__c); 
            }       
        }
         RollupSubAmtHandler.afterOperation(oppIdSet);
      }
     
}
Apex :
public class RollupSubAmtHandler {
    
    Public Static void afterOperation(Set<Id> setofOpportunityId)
    {
        Map<Id, List<AggregateResult>> revenuecostAmountMap = new Map<Id, List<AggregateResult>>();
        List<Opportunity> opptyListToUpdate = new List<Opportunity>();
   
       for(AggregateResult res : [SELECT Opportunity__c Opp, Product_Type__c value, AVG(Actual_Revenue_Rollup__c)revAvg , AVG(Actual_Cost_Rollup__c)costAvg FROM Sub_Opportunity__c  WHERE Opportunity__c IN : setofOpportunityId GROUP BY Opportunity__c, Product_Type__c]) {
        //opptyListToUpdate.add(new Opportunity(Id=(Id)res.get('Opportunity__c'), Actual_Revenue2__c= (Double)res.get('revAvg')));
        
          Id oppId = (ID)res.get('Opp');
          system.debug('revenuecostAmountMap=>'+ revenuecostAmountMap);
           If(revenuecostAmountMap.containsKey(oppId))
           {
              revenuecostAmountMap.get(oppId).add(res);
              
            } 
             else
             {
                 revenuecostAmountMap.put(oppId, new List<AggregateResult> { res });
             }
         
     } 
        System.debug('revenuecostAmountMap.size()=>>'+ revenuecostAmountMap.size());
            System.debug('revenuecostAmountMap=>>'+revenuecostAmountMap);
    
    for(Id opportunityId : revenuecostAmountMap.keySet())
    {
        Double sumOfRevenueAmount = calculateRevenue(revenuecostAmountMap.get(opportunityId));
        Double sumOfCostAmount = calculateCost(revenuecostAmountMap.get(opportunityId));
        Opportunity opportunityRecord = New Opportunity();
        opportunityRecord.Id = opportunityId;
        opportunityRecord.Actual_Cost2__c = sumOfCostAmount ;
        opportunityRecord.Actual_Revenue2__c = sumOfRevenueAmount ;
         opptyListToUpdate.add(opportunityRecord);
    }
    
    update opptyListToUpdate;
    
    
    }
    public Static Double calculateRevenue(List<AggregateResult> revenueList)
    {
        Double sumofrevenue = 0.0;
        for(AggregateResult ar : revenueList)
        {
            system.debug('each aggregate revenue value => '+ (Double)ar.get('revAvg'));
            sumofrevenue += (Double)ar.get('revAvg');
        }
        return sumofrevenue;
    }
    public Static Double calculateCost(List<AggregateResult> costList)
    {
        Double sumofcost = 0.0;
        for(AggregateResult ar : costList)
        {
            system.debug('each aggregate cost value => '+ (Double)ar.get('costAvg'));
            sumofcost += (Double)ar.get('costAvg');
        }
        return sumofcost;

    } 
}
AnkaiahAnkaiah (Salesforce Developers) 
Hi Mohini,

try with below code.
 
@isTest
public class RollupSubAmtHandlerTest
{
    @isTest
    public static void CreateOpportunityTestMethod()
    {
        Account objAccount = new Account();
        objAccount.Name = 'Test Acc';
        insert objAccount;
        System.AssertEquals(objAccount.Name, 'Test Acc');
        
        Opportunity objOpportunity = new Opportunity();
        objOpportunity.Name = 'Test Opp';
        objOpportunity.Accountid = objAccount.id;
        objOpportunity.StageName = 'Prospecting';
        objOpportunity.CloseDate = system.Today()+3;
        insert objOpportunity;
        System.AssertEquals(objOpportunity.Name, 'Test Opp');
		
		Sub_Opportunity__c subopp = new Sub_Opportunity__c();
		subopp.Name = 'test';
		subopp.Opportunity__c = objOpportunity.id;
		subopp.Actual_Cost_Rollup__c = 4000;
		subopp.Actual_Revenue_Rollup__c = 5000;
		subopp.Product_Type__c = 'picklistvalue';
		
		insert subopp;
    }
	
}

If this helps, Please mark it as best answer.

Thanks!!​​​​​​​

 
MohiniMohini
Hi Ankaiah ,

Thanks for taking the effort to write the test class.. Just a quick change ..Actual cost and actual revenue rollup are rollup fields  of opportunity product object for cost and revenue hence not writable . Can you please help me to incorporate that as I am getting this error " Field is not writeable: Sub_Opportunity__c.Actual_Cost_Rollup__c at line 23 column 16"
mukesh guptamukesh gupta
Hi Mohani,

Please use below code:-

you need to check data type of  Actual_Cost_Rollup__c field, I think it may be formula field that's why not able to write
@isTest
public class RollupSubAmtHandlerTest
{
    @isTest
    public static void CreateOpportunityTestMethod()
    {
        Account acc= new Account();
        acc.Name = 'Test Acc';
        insert acc;
        
        Opportunity opp= new Opportunity();
        opp.Name = 'Testopp1';
        opp.Accountid = acc.id;
        opp.Amount = 5000;
        opp.StageName = 'Prospecting';
        opp.CloseDate = system.Today()+1;
        insert opp;
        System.AssertEquals(opp.Name, 'Testopp1');
		
		Sub_Opportunity__c subopp = new Sub_Opportunity__c();
		subopp.Name = 'test';
		subopp.Opportunity__c = objOpportunity.id;
		subopp.Product_Type__c = 'picklistvalue';
		
		insert subopp;
    }
	
}

if you need any assistanse, Please let me know!!

Kindly mark my solution as the best answer if it helps you.

Thanks
Mukesh
MohiniMohini
Hi Mukesh , 

Can you help me to incorporate the Actual cost rollup and revenue fields of sub opportunity object  as they are rollup formula fields of opportunity product object cost and revenue fields . Exampla- the opportunity product object cost fields gets added and displayed at actual cost rollup field in sub opportunity object