0

I have a test class for a batch apex. When deploying to production, I am getting a 69% code coverage. So I am a few short of the 75%. The problem is when I run the test class it is taking hours/days to execute this. I am not sure how to make this test class or even the class better so that it takes quicker to run and more importantly gets over 75% coverage. Also, is there a way to check code coverage/lines covered without running the test class?

This is the main batch apex:

/* This class is used to update the contracts' pricebooks for renewals and amendments.
 */
global class UpdateContractPB_Batch implements Database.Batchable<sObject> { 
        
    global Iterable<SObject> start(Database.BatchableContext BC){
        id CurrPB = [SELECT Id FROM Pricebook2 WHERE IsActive = TRUE AND Current_Price_Book__c = TRUE LIMIT 1].Id;
        System.debug('Current Pricebook: ' + CurrPB);
        
        IF(test.isRunningTest()){
            return [SELECT ID, SBQQ__AmendmentPricebookId__c , SBQQ__RenewalPricebookId__c FROM Contract WHERE (Status = 'Activated' OR Status = 'Draft') AND RecordTypeID = '0120c000001ZWXKAA4' AND SBQQ__RenewalQuoted__c = FALSE AND (SBQQ__AmendmentPricebookId__c !=:CurrPB OR SBQQ__RenewalPricebookId__c !=:CurrPB) LIMIT 1];
        }else{
            return [SELECT ID, SBQQ__AmendmentPricebookId__c , SBQQ__RenewalPricebookId__c FROM Contract WHERE (Status = 'Activated' OR Status = 'Draft') AND RecordTypeID = '0120c000001ZWXKAA4' AND SBQQ__RenewalQuoted__c = FALSE AND (SBQQ__AmendmentPricebookId__c !=:CurrPB OR SBQQ__RenewalPricebookId__c !=:CurrPB)];
        }
        
    }
    
    global void execute(Database.BatchableContext BC, List<Contract> updateContractPBs) {    
        // process each batch of records
        id CurrPB2 = [SELECT Id FROM Pricebook2 WHERE IsActive = TRUE AND Current_Price_Book__c = TRUE LIMIT 1].Id;
        System.debug('Current Pricebook: ' + CurrPB2);
        
        for (Contract ucp:updateContractPBs){UpdateContractPricebookUtil.ProcessUpdateContractPricebook(ucp,CurrPB2);}
    
    }
    global void finish(Database.BatchableContext BC) {
        // execute any post-processing operations
  }
  global static void run()
  {
    UpdateContractPB_Batch batchjob = new UpdateContractPB_Batch();
    Integer BatchSize = 10;
    Database.executeBatch(batchjob,BatchSize);
  }
}

here is the utility class:

public class UpdateContractPricebookUtil  {

public static void ProcessUpdateContractPricebook(Contract updateContractPB, id CurrentPB)
{
          updateContractPB.SBQQ__AmendmentPricebookId__c = CurrentPB;
          updateContractPB.SBQQ__RenewalPricebookId__c = CurrentPB;
          
        try {
            // Update the Contract Record
            update updateContractPB;
        
        } catch(Exception e) {
            System.debug(e);
        }
         
    }
   
 }

here is the scheduler class:

//declaration of scheduler class

global class UpdateContractPBSched implements schedulable

{

global void execute(SchedulableContext sc) {
    UpdateContractPB_Batch.run();
  }

}

here is the test class for the batch apex which is at 69%:

@isTest 
public class UpdateContractPB_Batch_t {

  @IsTest
  static void test_UpdateContractPB_Batch() {
  
  Id userId = '0050c00000Du0Rz';
        User user1 = [select id from user where id = :userId];
        System.runAs(user1) {  
        
        fferpcore__ExchangeRateGroup__c exrg = new fferpcore__ExchangeRateGroup__c(CurrencyISOCode = 'USD', fferpcore__DefaultCurrency__c = 'USD - U.S. Dollar', Name = 'FF Shared Test Group', fferpcore__SelectedCurrencies__c = 'USD - U.S. Dollar');
        insert exrg;
        c2g__codaCompany__c company = new c2g__codaCompany__c();
        company.Name = 'ApexTestCompany';
        company.RecordTypeId = Schema.SObjectType.c2g__codaCompany__c.RecordTypeInfosByName.get('SUT').RecordTypeId;
        insert company;
        company.c2g__ExchangeRateGroup__c = exrg.Id;
        update company;
        c2g__codaAccountingCurrency__c curr = new c2g__codaAccountingCurrency__c(c2g__OwnerCompany__c  = company.Id, Name = 'USD', CurrencyIsoCode = 'USD', c2g__Home__c = TRUE, c2g__UnitOfWork__c = 1, c2g__DecimalPlaces__c = 2);
        c2g__codaUserCompany__c usercmpy = new c2g__codaUserCompany__c(c2g__Company__c = company.Id, c2g__User__c = userId);
        
        List<fferpcore__ExchangeRateGroup__c> LsExchRateGroup = [Select Id, Name From fferpcore__ExchangeRateGroup__c Where Name like 'FF Shared %' Order By CreatedDate DESC limit 1]; 
        Id ExGroup = LsExchRateGroup[0].Id;
        
        Id caseOnboardingRecordTypeId = Schema.SObjectType.Case.getRecordTypeInfosByName().get('Onboarding').getRecordTypeId();
        
        Product2 prodObj = new Product2(
                 Name = 'Test Product'
                ,ProductCode = 'abc' 
                ,isActive = TRUE
                ,SBQQ__QuantityEditable__c = TRUE
                ,SBQQ__SubscriptionPricing__c = 'Fixed Price'
                ,SBQQ__SubscriptionTerm__c = 12
                ,SBQQ__SubscriptionType__c = 'Renewable');
        insert prodObj;
        
        PricebookEntry strPrBkEntryObj = new PricebookEntry(
                       pricebook2Id = '01s300000009t4nAAA'
                      ,product2id  = prodObj.Id
                      ,unitprice = 2000
                      ,isactive  = TRUE);
        insert strPrBkEntryObj;   
        
        PricebookEntry PrBkEntryObj = new PricebookEntry(
                       pricebook2Id = '01s0c0000003vFfAAI'
                      ,product2id  = prodObj.Id
                      ,unitprice = 2000
                      ,isactive  = TRUE);
        insert PrBkEntryObj;
        
        Account a = new Account(RecordTypeId = '012300000002yUcAAI', Support_Level__c='Basic', Type = 'Customer', Name = 'Contract Test Account', Region__c = 'NAM', Ownership = 'Private', Website = 'https://www.financialforce.com', CurrencyIsoCode = 'USD', Preferred_Currency__c = 'USD', NumberOfEmployees = 100, FF_Customer_Success_Manager__c = userId, SFDC_Edition__c = 'Enterprise Edition');
        insert a;
        
        Case caseObj = new Case();
                caseObj.accountId = a.Id;
                caseObj.status = 'Unassigned';
                caseObj.type = 'Onboarding';
                caseObj.recordTypeId = caseOnboardingRecordTypeId;
                caseObj.priority = 'Medium';
                caseObj.contactId = '0034Q000036PKwqQAG';
              
         insert caseObj;
        
        Opportunity o = new Opportunity(RecordTypeId = '01230000000YdHSAA0', AccountId = a.id, Type = 'Renewal', Name = 'Test Renewal', CloseDate = date.today(), StageName = '01 - (Renewal) Opportunity Assessment', CurrencyIsoCode = 'USD', inCurrencyRate__c = 1, Probability = 85, Welcome_Email_Contact__c = '0034Q000036PKwqQAG', Onboarding_Contact__c = '0034Q000036PKwqQAG');
        insert o;
        
        SBQQ__Quote__c q = new SBQQ__Quote__c(RecordTypeId = '0120c000001ZWXcAAO', SBQQ__Type__c = 'Quote', SBQQ__PriceBook__c = '01s0c0000003vFfAAI', SBQQ__PricebookId__c = '01s0c0000003vFfAAI', SBQQ__StartDate__c = date.today(), SBQQ__EndDate__c = date.today() + 365, SBQQ__SubscriptionTerm__c = 12);
        insert q;
        
        SBQQ__QuoteLine__c ql = new SBQQ__QuoteLine__c(SBQQ__Quote__c  = q.Id, SBQQ__Product__c = prodObj.Id);
        insert ql;

        SBQQ__QuoteLineGroup__c g = new SBQQ__QuoteLineGroup__c(SBQQ__Quote__c = q.id);
        insert g;
    
        Contract c = new Contract(RecordTypeId = '0120c000001ZWXKAA4', SBQQ__Opportunity__c = o.id, AccountId = a.id, SBQQ__Quote__c = q.id, Status = 'Draft', StartDate = date.today(), ContractTerm = 12);
        insert c;
        
        SBQQ__Subscription__c s = new SBQQ__Subscription__c(SBQQ__Contract__c = c.id, SBQQ__Account__c = a.id, SBQQ__SubscriptionStartDate__c = date.today(), SBQQ__SubscriptionEndDate__c = date.today() + 365, SBQQ__SubscriptionType__c = 'Renewable', SBQQ__CustomerPrice__c = 2000, SBQQ__ListPrice__c = 2000, SBQQ__NetPrice__c = 2000, SBQQ__Number__c = 1, Paid_Months__c = 12, SBQQ__Product__c = prodObj.Id, SBQQ__PricingMethod__c = 'List', SBQQ__ProductSubscriptionType__c = 'Renewable', SBQQ__ProrateMultiplier__c = 1, SBQQ__Quantity__c = 1, Renewable_Subscription_Checkbox__c = TRUE, SBQQ__SpecialPrice__c = 2000, SBQQ__QuoteLine__c = ql.Id);
        insert s;
        
        Pricebook2 p = new Pricebook2(Name = 'Test Price Book', IsActive = TRUE, Current_Price_Book__c = TRUE);
        insert p;
        
        System.debug('Current Pricebook: ' + p.Id);
        system.assertNotEquals(c.SBQQ__RenewalPricebookId__c, p.Id);
        system.assertNotEquals(c.SBQQ__AmendmentPricebookId__c, p.Id);
        
        test.startTest();
        
        List <Pricebook2> p1 = [SELECT Id FROM Pricebook2 WHERE IsActive = TRUE AND Current_Price_Book__c = TRUE LIMIT 1];
        System.debug('Current Pricebook: ' + p1.size());
        system.assertEquals(TRUE, p1.size() > 0);
        
        List <Contract> c1 = [SELECT ID, SBQQ__AmendmentPricebookId__c , SBQQ__RenewalPricebookId__c FROM Contract WHERE (Status = 'Activated' OR Status = 'Draft') AND RecordTypeID = '0120c000001ZWXKAA4' AND SBQQ__RenewalQuoted__c = FALSE AND (SBQQ__AmendmentPricebookId__c !=:p1[0].id AND SBQQ__RenewalPricebookId__c !=:p1[0].id) LIMIT 1];
        System.debug('New Contract: ' + c1.size());
        system.assertEquals(TRUE, c1.size() > 0);
        
        UpdateContractPB_Batch batchjob = new UpdateContractPB_Batch();
        Database.executeBatch(batchjob,1);
        
        //UpdateContractPB_Batch.run();
        
        UpdateContractPricebookUtil.ProcessUpdateContractPricebook(c,p.id);
        
        List <Contract> c2 = [SELECT ID, SBQQ__AmendmentPricebookId__c , SBQQ__RenewalPricebookId__c FROM Contract WHERE (Status = 'Activated' OR Status = 'Draft') AND RecordTypeID = '0120c000001ZWXKAA4' AND SBQQ__RenewalQuoted__c = FALSE AND (SBQQ__AmendmentPricebookId__c =:p1[0].id AND SBQQ__RenewalPricebookId__c =:p1[0].id) LIMIT 1];
        System.debug('New Contract: ' + c2.size());
        system.assertEquals(TRUE, c2.size() > 0);
        
        system.assertEquals(c2[0].SBQQ__RenewalPricebookId__c, p1[0].Id);
        system.assertEquals(c2[0].SBQQ__AmendmentPricebookId__c, p1[0].Id);
        
        test.stopTest();
        
        }
        
    }
}

Can someone please let me know what changes i can make to increase it to over 75%?

would the modified test class look like this?

@isTest 
public class UpdateContractPB_Batch_t {

  @IsTest
  static void test_UpdateContractPB_Batch() {
  
  Id userId = '0050c00000Du0Rz';
        User user1 = [select id from user where id = :userId];
        System.runAs(user1) {  
        
        fferpcore__ExchangeRateGroup__c exrg = new fferpcore__ExchangeRateGroup__c(CurrencyISOCode = 'USD', fferpcore__DefaultCurrency__c = 'USD - U.S. Dollar', Name = 'FF Shared Test Group', fferpcore__SelectedCurrencies__c = 'USD - U.S. Dollar');
        insert exrg;
        c2g__codaCompany__c company = new c2g__codaCompany__c();
        company.Name = 'ApexTestCompany';
        company.RecordTypeId = Schema.SObjectType.c2g__codaCompany__c.RecordTypeInfosByName.get('SUT').RecordTypeId;
        insert company;
        company.c2g__ExchangeRateGroup__c = exrg.Id;
        update company;
        c2g__codaAccountingCurrency__c curr = new c2g__codaAccountingCurrency__c(c2g__OwnerCompany__c  = company.Id, Name = 'USD', CurrencyIsoCode = 'USD', c2g__Home__c = TRUE, c2g__UnitOfWork__c = 1, c2g__DecimalPlaces__c = 2);
        c2g__codaUserCompany__c usercmpy = new c2g__codaUserCompany__c(c2g__Company__c = company.Id, c2g__User__c = userId);
        
        List<fferpcore__ExchangeRateGroup__c> LsExchRateGroup = [Select Id, Name From fferpcore__ExchangeRateGroup__c Where Name like 'FF Shared %' Order By CreatedDate DESC limit 1]; 
        Id ExGroup = LsExchRateGroup[0].Id;
        
        Id caseOnboardingRecordTypeId = Schema.SObjectType.Case.getRecordTypeInfosByName().get('Onboarding').getRecordTypeId();
        
        Product2 prodObj = new Product2(
                 Name = 'Test Product'
                ,ProductCode = 'abc' 
                ,isActive = TRUE
                ,SBQQ__QuantityEditable__c = TRUE
                ,SBQQ__SubscriptionPricing__c = 'Fixed Price'
                ,SBQQ__SubscriptionTerm__c = 12
                ,SBQQ__SubscriptionType__c = 'Renewable');
        insert prodObj;
        
        PricebookEntry strPrBkEntryObj = new PricebookEntry(
                       pricebook2Id = '01s300000009t4nAAA'
                      ,product2id  = prodObj.Id
                      ,unitprice = 2000
                      ,isactive  = TRUE);
        insert strPrBkEntryObj;   
        
        PricebookEntry PrBkEntryObj = new PricebookEntry(
                       pricebook2Id = '01s0c0000003vFfAAI'
                      ,product2id  = prodObj.Id
                      ,unitprice = 2000
                      ,isactive  = TRUE);
        insert PrBkEntryObj;
        
        Account a = new Account(RecordTypeId = '012300000002yUcAAI', Support_Level__c='Basic', Type = 'Customer', Name = 'Contract Test Account', Region__c = 'NAM', Ownership = 'Private', Website = 'https://www.financialforce.com', CurrencyIsoCode = 'USD', Preferred_Currency__c = 'USD', NumberOfEmployees = 100, FF_Customer_Success_Manager__c = userId, SFDC_Edition__c = 'Enterprise Edition');
        insert a;
        
        Case caseObj = new Case();
                caseObj.accountId = a.Id;
                caseObj.status = 'Unassigned';
                caseObj.type = 'Onboarding';
                caseObj.recordTypeId = caseOnboardingRecordTypeId;
                caseObj.priority = 'Medium';
                caseObj.contactId = '0034Q000036PKwqQAG';
              
         insert caseObj;
        
        Opportunity o = new Opportunity(RecordTypeId = '01230000000YdHSAA0', AccountId = a.id, Type = 'Renewal', Name = 'Test Renewal', CloseDate = date.today(), StageName = '01 - (Renewal) Opportunity Assessment', CurrencyIsoCode = 'USD', inCurrencyRate__c = 1, Probability = 85, Welcome_Email_Contact__c = '0034Q000036PKwqQAG', Onboarding_Contact__c = '0034Q000036PKwqQAG');
        insert o;
        
        SBQQ__Quote__c q = new SBQQ__Quote__c(RecordTypeId = '0120c000001ZWXcAAO', SBQQ__Type__c = 'Quote', SBQQ__PriceBook__c = '01s0c0000003vFfAAI', SBQQ__PricebookId__c = '01s0c0000003vFfAAI', SBQQ__StartDate__c = date.today(), SBQQ__EndDate__c = date.today() + 365, SBQQ__SubscriptionTerm__c = 12);
        insert q;
        
        SBQQ__QuoteLine__c ql = new SBQQ__QuoteLine__c(SBQQ__Quote__c  = q.Id, SBQQ__Product__c = prodObj.Id);
        insert ql;

        SBQQ__QuoteLineGroup__c g = new SBQQ__QuoteLineGroup__c(SBQQ__Quote__c = q.id);
        insert g;
    
        Contract c = new Contract(RecordTypeId = '0120c000001ZWXKAA4', SBQQ__Opportunity__c = o.id, AccountId = a.id, SBQQ__Quote__c = q.id, Status = 'Draft', StartDate = date.today(), ContractTerm = 12);
        insert c;
        
        SBQQ__Subscription__c s = new SBQQ__Subscription__c(SBQQ__Contract__c = c.id, SBQQ__Account__c = a.id, SBQQ__SubscriptionStartDate__c = date.today(), SBQQ__SubscriptionEndDate__c = date.today() + 365, SBQQ__SubscriptionType__c = 'Renewable', SBQQ__CustomerPrice__c = 2000, SBQQ__ListPrice__c = 2000, SBQQ__NetPrice__c = 2000, SBQQ__Number__c = 1, Paid_Months__c = 12, SBQQ__Product__c = prodObj.Id, SBQQ__PricingMethod__c = 'List', SBQQ__ProductSubscriptionType__c = 'Renewable', SBQQ__ProrateMultiplier__c = 1, SBQQ__Quantity__c = 1, Renewable_Subscription_Checkbox__c = TRUE, SBQQ__SpecialPrice__c = 2000, SBQQ__QuoteLine__c = ql.Id);
        insert s;
        
        Pricebook2 p = new Pricebook2(Name = 'Test Price Book', IsActive = TRUE, Current_Price_Book__c = TRUE);
        insert p;
        
        System.debug('Current Pricebook: ' + p.Id);
        system.assertNotEquals(c.SBQQ__RenewalPricebookId__c, p.Id);
        system.assertNotEquals(c.SBQQ__AmendmentPricebookId__c, p.Id);
        
        
        List <Pricebook2> p1 = [SELECT Id FROM Pricebook2 WHERE IsActive = TRUE AND Current_Price_Book__c = TRUE LIMIT 1];
        System.debug('Current Pricebook: ' + p1.size());
        system.assertEquals(TRUE, p1.size() > 0);
        
        List <Contract> c1 = [SELECT ID, SBQQ__AmendmentPricebookId__c , SBQQ__RenewalPricebookId__c FROM Contract WHERE (Status = 'Activated' OR Status = 'Draft') AND RecordTypeID = '0120c000001ZWXKAA4' AND SBQQ__RenewalQuoted__c = FALSE AND (SBQQ__AmendmentPricebookId__c !=:p1[0].id AND SBQQ__RenewalPricebookId__c !=:p1[0].id) LIMIT 1];
        System.debug('New Contract: ' + c1.size());
        system.assertEquals(TRUE, c1.size() > 0);
        
        test.startTest();

        //UpdateContractPB_Batch batchjob = new //UpdateContractPB_Batch();
        //Database.executeBatch(batchjob,1);
        
        //UpdateContractPB_Batch.run();
        
        //UpdateContractPricebookUtil.ProcessUpdateContractPricebook(c,p.id);

Test.startTest(); System.schedule('TEST PB SCHED', '0 0 * * * ?', new UpdateContractPBSched()); Test.stopTest();

        List <Contract> c2 = [SELECT ID, SBQQ__AmendmentPricebookId__c , SBQQ__RenewalPricebookId__c FROM Contract WHERE (Status = 'Activated' OR Status = 'Draft') AND RecordTypeID = '0120c000001ZWXKAA4' AND SBQQ__RenewalQuoted__c = FALSE AND (SBQQ__AmendmentPricebookId__c =:p1[0].id AND SBQQ__RenewalPricebookId__c =:p1[0].id) LIMIT 1];
        System.debug('New Contract: ' + c2.size());
        system.assertEquals(TRUE, c2.size() > 0);
        
        system.assertEquals(c2[0].SBQQ__RenewalPricebookId__c, p1[0].Id);
        system.assertEquals(c2[0].SBQQ__AmendmentPricebookId__c, p1[0].Id);
        
        
        
        }
        
    }
}
1

You need to call Test.stopTest() before assertions. That said, you could increase your coverage a bit by calling scheduler instead of batch directly:

Test.startTest();
System.schedule('TEST PB SCHED', '0 0 * * * ?', new UpdateContractPBSched());
Test.stopTest();

Also, consider removing your try-catch block if you are only going to System.debug() the results away. You'll get slightly better coverage.

1
  • Hello @sfdcfox, So i just put my new version of the test class above. Is that what the test class should look like? Thank you – user3688231 Apr 19 at 13:41

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.