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
sonam gupthasonam guptha 

Code coverage issue for triggerhandler

Hi,

Can anyone help me to fix this issue,here am attaching the test class which am able to cover 50%,just help me out to cover the rest.
 
//trigger code
trigger UpdateTotalAmount on Opportunity (after insert,after update) {
     clsUpdateAccount.updateAccount(Trigger.new);
}

//APEX Class
public class clsUpdateAccount{
    public static void updateAccount(List<Opportunity> lstOpportunities) {
         List<Id> lstAccountIDs = new List<Id>();
         for(Opportunity opp: lstOpportunities) {
           lstAccountIDs.add(opp.AccountId);
         }
         
         Map<Id, Account> mapAccount = new Map<Id, Account>([SELECT Id, Name, TotalAmount__c FROM Account WHERE Id =:lstAccountIDs]);

         List<Account> lstAccounts = new List<Account>();
         for(AggregateResult result: [SELECT SUM(Amount) Amt, AccountId FROM Opportunity GROUP BY AccountId, StageName Having AccountId IN :mapAccount.keyset() AND StageName = 'Closed Won' ]) { 
            Account acc = mapAccount.get((Id)result.get('AccountID'));
            acc.TotalAmount__c = (Decimal)result.get('Amt');
            lstAccounts.add(acc);
         }
         if(lstAccounts.size() > 0){
            update lstAccounts;
         }
    }
}
 
static testmethod void oppamount(){
    Test.starttest();
    Account acc = new Account(Name = 'testacc' ,TotalAmount__c = 1000);
     insert acc;
    
   Opportunity opp = new Opportunity(RecordTypeId = '012E0000000Dke9', Name = 'name', CloseDate = Date.today(),
                        StageName = 'Prospecting', AccountId = acc.id, Amount = 1000, ForecastCategoryName = 'nextlevel', 
                        Opportunity_Source__c='Marketing Campaign (Inbound)');
        insert opp;
    
    
    Account acc1 = [SELECT id, Sum_of_Opportunity_Amount__c FROM Account WHERE Id = :acc.Id];
    // Verification
    System.assertEquals(acc1.TotalAmount__c, opp.amount);
     
    Test.stopTest();
    }
But here am getting below error:--
System.AssertException: Assertion Failed: Expected: null, Actual: 1000

Thanks
 
Best Answer chosen by sonam guptha
DeveloperSudDeveloperSud
Hi Sonam,

I just relised the problem. It seems the query you used is not correctly done .Kindly use the below Query and check.
for(AggregateResult result: [SELECT SUM(Amount) Amt, AccountId FROM Opportunity GROUP BY AccountId, opp_priority__c Having AccountId IN :mapAccount.keyset() AND  opp_priority__c = true]) {

Now coming to the test coverage for the formula field .We cant hardcoding the formula field in test class.As I can see you used the formula field opp_priority in the query when its value is true , you need to do the same for the test class also , like you need to crete the opportunity record like that after insert or update the formula field opp_priority becomes true.Let me give you my scenario, it will help you to understand. I created a same opp_priority__c formula checkbox field in the opportunity object and this field will be checked (true) when the oppotunity record will be created/updated with stage name as 'Closed Won' .So As you can see in my test class while creating /updating the opportunity record I made the stageName field set as closed won so that after insert /update for that record opp_priority__c field becomes automatically true. I dont know what scenario you used for that formula field but during testing you need to test like this.I mean u need to assign those field values so that for the test opportunity record the opp_priority__c field becomes true.Now coming to the test class ,there is no change for the test class for my scenario, only I used the same opportunity name twice :P ,you can change that in your class. Let me know if you have still some problem.

All Answers

DeveloperSudDeveloperSud
Hi,

Try the below code and let us know if this works for you.
 
@isTest
public class clsUpdateAccountTest {

    static testmethod void muUnittest1(){
        
        Account a= new Account ();
        a.name='Test Account';
        insert a;
        
        List<Opportunity>  opsToInsert = new List<Opportunity>();
        
        Opportunity ops= new Opportunity();
        ops.Name='Test Opportunity 1';
        ops.CloseDate=system.today();
        ops.StageName='Closed Won';
        ops.Amount=100;
        ops.AccountId=a.id;
        opsToInsert.add(ops);
        
        Opportunity opss= new Opportunity();
        opss.Name='Test Opportunity 1';
        opss.CloseDate=system.today();
        opss.StageName='Closed Won';
        opss.Amount=100;
        opss.AccountId=a.Id;
        opsToInsert.add(opss);
        
        Test.startTest();
         Insert opsToInsert;
        Test.stopTest();
        
        Account uAct=[select id,name,totalAmount__c from account where id=:a.id];
        system.assertEquals(200, uAct.TotalAmount__c);
        
        
    }
     static testmethod void muUnittest2(){
        
        Account a= new Account ();
        a.name='Test Account';
        insert a;
        
        List<Opportunity>  opsToInsert = new List<Opportunity>();
        List<Opportunity>  opsToUpdate = new List<Opportunity>();
         
        Opportunity ops= new Opportunity();
        ops.Name='Test Opportunity 1';
        ops.CloseDate=system.today();
        ops.StageName='Closed Won';
        ops.Amount=100;
        ops.AccountId=a.id;
        opsToInsert.add(ops);
         
        Opportunity opss= new Opportunity();
        opss.Name='Test Opportunity 1';
        opss.CloseDate=system.today();
        opss.StageName='Closed Won';
        opss.Amount=100;
        opss.AccountId=a.Id;
        opsToInsert.add(opss);
        
        Test.startTest();
         insert opsToInsert;
         opss.Amount=200;
         opsToUpdate.add(opss);
         update opsToUpdate;
        Test.stopTest();
        
        Account uAct=[select id,name,totalAmount__c from account where id=:a.id];
        system.assertEquals(300, uAct.TotalAmount__c);
        
        
    }
      
}

 
sonam gupthasonam guptha
Hi  DeveloperSud,

Still am seeing the same error.
System.AssertException: Assertion Failed: Expected: 200, Actual: null
And line 17 on my triggerhandler i changed the where condition from StageName = 'Closed Won' to opp_priority__c(Formula Field) = true,this may affect in any way,please suggest some solution.
for(AggregateResult result: [SELECT SUM(Amount) Amt, AccountId FROM Opportunity GROUP BY AccountId, StageName Having AccountId IN :mapAccount.keyset() AND opp_priority__c = true]) {

Thanks for the quick response!
 
DeveloperSudDeveloperSud
Hi,

This is really Strange .This is working fine in my org.Can u just check and let us know if the trigger is still active? If this not kindly check the active checkbox for the trigger and make the trigger active in the org.Run the test class after that. Thanks!!!
sonam gupthasonam guptha
DeveloperSud,

Trigger is Active and covering 100%,but the problem is with triggerhandler,i think i need to include the formula field opp_priority__c = true,but its not allowing me to place that field on test class,it keep on throwing an error,how can i write formula field in test class?
Error: Compile Error: Field is not writeable:
I used system.asserNOTEquals()?its passing the test class but code coverage is not improving?
 
DeveloperSudDeveloperSud
Hi Sonam,

I just relised the problem. It seems the query you used is not correctly done .Kindly use the below Query and check.
for(AggregateResult result: [SELECT SUM(Amount) Amt, AccountId FROM Opportunity GROUP BY AccountId, opp_priority__c Having AccountId IN :mapAccount.keyset() AND  opp_priority__c = true]) {

Now coming to the test coverage for the formula field .We cant hardcoding the formula field in test class.As I can see you used the formula field opp_priority in the query when its value is true , you need to do the same for the test class also , like you need to crete the opportunity record like that after insert or update the formula field opp_priority becomes true.Let me give you my scenario, it will help you to understand. I created a same opp_priority__c formula checkbox field in the opportunity object and this field will be checked (true) when the oppotunity record will be created/updated with stage name as 'Closed Won' .So As you can see in my test class while creating /updating the opportunity record I made the stageName field set as closed won so that after insert /update for that record opp_priority__c field becomes automatically true. I dont know what scenario you used for that formula field but during testing you need to test like this.I mean u need to assign those field values so that for the test opportunity record the opp_priority__c field becomes true.Now coming to the test class ,there is no change for the test class for my scenario, only I used the same opportunity name twice :P ,you can change that in your class. Let me know if you have still some problem.
This was selected as the best answer
sonam gupthasonam guptha
Thanks a tonn,finally its working.