salesforceapexapex-codesalesforce-service-cloud

Batch apex with aggregate query which work perfect but when I'm trying to write the test class for this batch apex test class is failing


**When I run the below test class it return empty list in query method. I there any different way to write test class for aggregate batch apex **
global class Batch_Agent implements Database.Batchable {

global Iterable<AggregateResult> start(Database.BatchableContext BC){ 
    
    string query='SELECT SUM(Expected_Agency_Commission__c) Sum_of_Agency_Commission, SUM(Monthly_Premium__c) Sum_of_Monthly_Permium ,Sales_Agent__c FROM InsurancePolicy WHERE Is_Agency_commission_Paid__c=False and Effectuated__c=true and Submitted_Date__c >= 2021-02-02 and Submitted_Date__c <= 2021-05-01 and Sales_Agent__r.Sales_Agent_User__r.IsActive = true and Expected_Agency_Commission__c!= 0 and Expected_Agency_Commission__c!= null Group by Sales_Agent__c, Is_Agency_commission_Paid__c  ';
    
    return new AggregateResultIterable(query); 
} 
global void execute(Database.BatchableContext BC, List<Sobject> scope){

    List<Sobject> policyLists = scope;
    
    List<contact> agentContactList = new List<contact>();
    
    List<Contact> conlist = [SELECT Id, Name, Seat_Cost__c, Tier__c FROM Contact WHERE Sales_Agent_User__r.IsActive = true and RecordType.name ='Sales Agent'];
    
    List<Bonus_Amount__c> bonusList = [SELECT Id , Name, Commission_Amount__c,Commission_End_Amount__c,Bonus_Percentage__c FROM Bonus_Amount__c ];
    
    List<Agent_Commission__c> agentComList = new List<Agent_Commission__c>();
    
    list<Id> salesAgentIds = new List<Id>();
    
    for(Sobject policy:policyLists){
        if(policy.Get('Sales_Agent__c')!=null){
            Id conIds;
            Decimal seatCost;
            String agentTier;
            Decimal comissionAmount;
            Decimal bonusPercentage;
            Agent_Commission__c agentComm = new Agent_Commission__c();
            agentComm.Sum_of_Expected_Agency_Commission__c = (Decimal)policy.Get('Sum_of_Agency_Commission');
            agentComm.Sum_of_Monthly_Permium__c = (Decimal)policy.Get('Sum_of_Monthly_Permium');
            conIds = (Id)policy.Get('Sales_Agent__c');
            for(contact con:conlist ){
                if(con.Id==conIds){
                    seatCost=con.Seat_Cost__c;
                    agentTier=con.Tier__c;
                }
            }
            agentComm.Commisionable_Amount__c = ((Decimal)policy.Get('Sum_of_Agency_Commission')-seatCost);
            comissionAmount = agentComm.Commisionable_Amount__c ;
            for(Bonus_Amount__c bnus:bonusList){
                if(bnus.Name == agentTier){
                    if (comissionAmount < 0 ){
                        bonusPercentage = 0;
                    }
                    else if( comissionAmount >= bnus.Commission_Amount__c && comissionAmount < bnus.Commission_End_Amount__c){
                        bonusPercentage = bnus.Bonus_Percentage__c;
                    }
                }
            }
            agentComm.Bonus_Percentage__c = bonusPercentage;
            agentComm.Bonus_Amount__c = comissionAmount*bonusPercentage;
            agentComm.Sales_Agent__c = (String)policy.Get('Sales_Agent__c');
            salesAgentIds.add(agentComm.Sales_Agent__c);
            agentComm.Name  = String.valueOf(System.now());
            agentComList.add(agentComm);
            
        }
    }
    
    Insert agentComList;
    
    List<InsurancePolicy> policyUpdates = [SELECT ID, Name, test_Is_Agency_commission_Paid__c, Is_Agency_commission_Paid__c, Sales_Agent__c FROM InsurancePolicy 
                                           WHERE Is_Agency_commission_Paid__c= false and Sales_Agent__r.Sales_Agent_User__r.IsActive = true and 
                                           Expected_Agency_Commission__c!= 0 and Expected_Agency_Commission__c!= null and Effectuated__c=true and 
                                           Submitted_Date__c > 2021-01-01 and Sales_Agent__c in :salesAgentIDs ];
    for(InsurancePolicy polupdate :policyUpdates ){
        polupdate.Is_Agency_commission_Paid__c = false;
    }
    
    Update policyUpdates;
    
}     

global void finish(Database.BatchableContext BC){
    
}    

}

==================================================

@isTest(SeeAllData = FALSE) public class lig_AgentCommissionTrigerHandlerTest {

private static Contact createContact(String lastName,  Boolean withInsert ){
    Contact newContact = new Contact(
        LastName = lastName,
        recordTypeId = Schema.getGlobalDescribe().get('Contact').getDescribe().getRecordTypeInfosByName().get('Sales Agent').getRecordTypeId(),
        Seat_Cost__c = 22000,
        Tier__c = 'T1' 
    );
    
    if(withInsert){
        insert newContact;
    }
    
    return newContact;
}
private static Bonus_Amount__c createBonusList(Boolean  withInsert){
    Bonus_Amount__c newBonusAmount = new Bonus_Amount__c(
        Name = 'T1',
        Commission_Amount__c = 2100,
        Commission_End_Amount__c = 3500,
        Bonus_Percentage__c = 0.03
    );
    
    if(withInsert){
        insert newBonusAmount ;
    }
    
    return newBonusAmount ;
}

private static InsurancePolicy createInsurancePolicy(String name, Id nameInsuredId, Id saleAgentID,Integer agencycom, Integer mnthlyper,  Boolean withInsert){
    InsurancePolicy newPolicy = new InsurancePolicy(
        NameInsuredId = nameInsuredId,
        Name = name,
        Sales_Agent__c = saleAgentID,
        Expected_Agency_Commission__c = 12345,
        Monthly_Premium__c = 231,
        Is_Agency_commission_Paid__c = False 
        //Effectuated__c = True
        
    );
    
    if(withInsert){
        insert newPolicy;
    }
    
    return newPolicy;
}
@TestSetup
private static void createTestData() {
    //create test account
    //create test account
    Account policyHolder = lig_TestDataFactory.createPersonAccount('Test',
                                                                   'Account',
                                                                   'test@account.com',
                                                                   '1234567890',
                                                                   '1234567980',
                                                                   TRUE);
    
    Contact agentContact = lig_AgentCommissionTrigerHandlerTest.createContact('Test',
                                                                              TRUE);
    
    Bonus_Amount__c bonusAmount = lig_AgentCommissionTrigerHandlerTest.createBonusList(TRUE);
    
    
    List<InsurancePolicy> testPolicies = new List<InsurancePolicy>();
    
    testPolicies.add(lig_AgentCommissionTrigerHandlerTest.createInsurancePolicy('Test Policy 1', 
                                                                                policyHolder.Id,
                                                                                agentContact.Id,
                                                                                1234,
                                                                                212,
                                                                                FALSE));
    
    testPolicies.add(lig_AgentCommissionTrigerHandlerTest.createInsurancePolicy('Test Policy 2', 
                                                                                policyHolder.Id,
                                                                                agentContact.Id,
                                                                                2311,
                                                                                123,
                                                                                FALSE));
    
    insert testPolicies;
}
@isTest static  void testCreateRenewalOppty()
{
    List<Sobject> policies = [SELECT SUM(Expected_Agency_Commission__c) Sum_of_Agency_Commission, SUM(Monthly_Premium__c) Sum_of_Monthly_Permium ,Sales_Agent__c FROM InsurancePolicy
                              WHERE Is_Agency_commission_Paid__c=False Group by Sales_Agent__c];
    
    
    
    List<Bonus_Amount__c> bonusList = [SELECT Id , Name, Commission_Amount__c,Commission_End_Amount__c,Bonus_Percentage__c FROM Bonus_Amount__c ];
    
    list<Id> salesAgentIds = new List<Id>();
    Test.startTest();
    
    Batch_Agent baAgent = new Batch_Agent();
    ID jobID = database.executebatch(baAgent,5);
    Test.stopTest();
}

}


Solution

  • It returns an empty list because the test data you are creating does not match the query filters:

    SELECT SUM(Expected_Agency_Commission__c) Sum_of_Agency_Commission, 
           SUM(Monthly_Premium__c) Sum_of_Monthly_Permium,
           Sales_Agent__c 
    FROM InsurancePolicy 
    WHERE Is_Agency_commission_Paid__c=False 
          and Effectuated__c=true 
          and Submitted_Date__c >= 2021-02-02 
          and Submitted_Date__c <= 2021-05-01 
          and Sales_Agent__r.Sales_Agent_User__r.IsActive = true 
          and Expected_Agency_Commission__c!= 0 
          and Expected_Agency_Commission__c!= null 
    Group by Sales_Agent__c, Is_Agency_commission_Paid__c
    

    Your test-context InsurancePolicy records must match all of the WHERE filters. Note as one example that your test data factory doesn't populate the Submitted_Date__c field. (It's unclear why you have hard-coded these values in your query).