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
Sudeep SinghSudeep Singh 

Test Class coverage 60%

Batch Class:- 

 

/* Class Type :- Batch
* Date :- 
* Description :- Creates a new order if Contract Status is Activated after one month and update Next Order Date
* Author :- 
*/ 
global class AutoSubscriptionForOrderCreation implements Database.Batchable<sObject>,schedulable,database.stateful {
    Public string errmsg = '';
    Public integer OrderCount = 0;
    Public void execute(SchedulableContext sc) 
    { 
        database.executebatch(new AutoSubscriptionForOrderCreation());
    }
    global Database.QueryLocator start(Database.BatchableContext bc) {
        Date orderCreationDate = system.today().addDays(3);
        //system.debug('output'+[SELECT Id,Status,Next_Order_Date__c,Service__r.id,AccountId,ShippingAddress,BillingAddress,Insurance__c From Contract Where Status = 'Activated' And Next_Order_Date__c = TODAY]);
        if(Test.isRunningTest()){
            return Database.getQueryLocator([SELECT Id,Status,Next_Order_Date__c,Service__r.id,AccountId,ShippingAddress,BillingAddress,Insurance__c,Group_ID__c,Policy_ID__c,Insurance_Provider__c,BillingState,BillingCity,BillingStreet,BillingCountry,BillingPostalCode,BillingLatitude,BillingLongitude,ShippingStreet,ShippingState,ShippingCity,ShippingCountry,ShippingPostalCode,ShippingLatitude,ShippingLongitude,CustomerSignedId From Contract]);
        }else{
            //System.debug('This is executing');
           return Database.getQueryLocator([SELECT Id,Status,Next_Order_Date__c,Service__r.id,AccountId,ShippingAddress,BillingAddress,Insurance__c,Group_ID__c,Policy_ID__c,Insurance_Provider__c,BillingState,BillingCity,BillingStreet,BillingCountry,BillingPostalCode,BillingLatitude,BillingLongitude,ShippingStreet,ShippingState,ShippingCity,ShippingCountry,ShippingPostalCode,ShippingLatitude,ShippingLongitude,CustomerSignedId From Contract Where Status = 'Activated' And Next_Order_Date__c =: orderCreationDate]); 
        }
    }
    
    global void execute(Database.BatchableContext bc, List<Contract> contractlst) {
        try{
            
        
        List<Order> orderlsttoinsert = new List<Order>();
        List<OrderItem> orderItemsToInsert = new List<OrderItem>();
        List<Contract> contractupdatelst = new List<Contract>();
        List<Order> ordertoupdate= new List<Order>();
        map<Id, Id> contractProdMap = New map<Id, Id>();
        if(contractlst.size() > 0){
            
            Pricebook2 priceBook = [select id, name from Pricebook2 where isStandard = true limit 1];
            List<PriceBookEntry> priceBookEntryList = [SELECT Product2.Id, Product2.Name, UnitPrice FROM PriceBookEntry WHERE Pricebook2Id =:priceBook.id];            
            //System.debug('priceBookEntryList'+priceBookEntryList);
            //Set <Id> accid  = new set <Id>();
            //List
            for(Contract con: contractlst){
                //Insert Orders
                Order orderObj = new Order();
                orderObj.AccountId = con.AccountId;
                orderObj.Status = 'Draft';
                orderObj.ContractId = con.Id;
                orderObj.EffectiveDate = System.today();
                orderObj.Pricebook2Id =  priceBook.id;
                orderObj.Insurance__c =  con.Insurance__c;
                orderObj.Insurance_Group_Number__c = con.Group_ID__c;
                orderObj.Insurance_ID__c = con.Policy_ID__c;
                orderObj.Insurance_Name__c = con.Insurance_Provider__c;
                orderObj.Type = 'Subscription Order';
                orderObj.BillingStreet = con.BillingStreet;
                orderObj.BillingState = con.BillingState;
                orderObj.BillingCity = con.BillingCity;
                orderObj.BillingCountry = con.BillingCountry;
                orderObj.BillingPostalCode = con.BillingPostalCode;
                orderObj.BillingLatitude = con.BillingLatitude;
                orderObj.BillingLongitude = con.BillingLongitude;
                orderObj.ShippingStreet = con.ShippingStreet;
                orderObj.ShippingState = con.ShippingState;
                orderObj.ShippingCity = con.ShippingCity;
                orderObj.ShippingCountry = con.ShippingCountry;
                orderObj.ShippingPostalCode = con.ShippingPostalCode;
                orderObj.ShippingLatitude = con.ShippingLatitude;
                orderObj.ShippingLongitude = con.ShippingLongitude;
                //orderObj.ShipToContactId = con.account.PersonContactId;
                //orderObj.BillToContactId = con.account.PersonContactId;
                orderObj.EffectiveDate = con.Next_Order_Date__c;
                orderlsttoinsert.add(orderObj);
                
                //Create Contract and Product Map
                //System.debug('');
                for(PriceBookEntry pBookEntry : priceBookEntryList){
                    if(pBookEntry.Product2.Id == con.Service__r.Id){
                        contractProdMap.put(con.Id, pBookEntry.Id);
                        //System.debug('running');
                    }
                }
                
                // Update order date to next month's nearest Wednesday
                Date nextOrderDate = ((System.today().addMonths(1)).toStartOfWeek().addDays(3));
                con.Next_Order_Date__c = nextOrderDate;
                contractupdatelst.add(con);
                
            }
            if(orderlsttoinsert.size() > 0){
                insert orderlsttoinsert; 
                OrderCount = OrderCount+orderlsttoinsert.size();
                           
                for(Order O: orderlsttoinsert){
                    //System.debug('contractProdMap.get(O.ContractId)'+contractProdMap.get(O.ContractId));
                    //Insert Order Items
                    OrderItem oi = new OrderItem();
                    oi.OrderId = O.id;
                    oi.Quantity = 1;
                    oi.UnitPrice = 1;
                    oi.Product2id = O.Contract.Service__c;
                    oi.PricebookEntryId = contractProdMap.get(O.ContractId);
                    oi.sstation__Currency_Type__c = 'USD';
                    orderItemsToInsert.add(oi);
                }    
            }
            if(orderItemsToInsert.size() > 0){
                insert orderItemsToInsert;
            }
            if(contractupdatelst.size() > 0){
                update contractupdatelst;
            }
            if(orderlsttoinsert.size() > 0){
            for(Order Order: orderlsttoinsert){
                Order.Status='Order Placed';
                ordertoupdate.add(Order);
            } 
            update ordertoupdate; 
                
        }   
        }
        }catch (exception e){
            errmsg = e.getMessage();
            //System.debug('errmsg'+errmsg);
            Batch_Message__c batch = new Batch_Message__c();
            batch.Batch_Status__c = 'Failed';
            batch.Failed_Description__c = errmsg;
            insert batch;
        }
    }    
    global void finish(Database.BatchableContext bc) {
        if (errmsg == ''){
            Batch_Message__c batch = new Batch_Message__c();
            batch.Batch_Status__c = 'Success';  
            batch.Order_Count__c = OrderCount;
            insert batch;
       
        }        
    }
}

 

Test class:- 

@isTest
public class Test_AutoSubscriptionForOrderCreation {
    @isTest
    static void testMethod1()
            {
        String recordTypeId = Schema.getGlobalDescribe().get('Account').getDescribe().getRecordTypeInfosByName().get('Person Account').getRecordTypeId();
        Account acc= new Account(
        RecordTypeID=recordTypeId ,
        FirstName='Test FName',
        LastName='Test LName',
        PersonMailingStreet='test@yahoo.com',
        PersonMailingPostalCode='12345',
        PersonMailingCity='SFO',
        PersonEmail='test@yahoo.com',
        PersonHomePhone='1234567',
        PersonMobilePhone='12345678'
        );
        insert acc;
                
        Contact con = new Contact();
        //con.AccountId = acc.Id;
        con.LastName = 'Test';
        con.Birthdate = system.today();
        insert con;
                
        Product2 op = new Product2();
        op.Name = 'Test';
        op.IsActive = true;
        op.ProductCode = 'Test';
        insert op;
                
        Pricebook2 standardPricebook = new Pricebook2(
        Id = Test.getStandardPricebookId(),
        IsActive = true
        );
   
        update standardPricebook;   
        PricebookEntry standardPrice = new PricebookEntry();
        standardPrice.Pricebook2Id = standardPricebook.id;
        standardPrice.Product2Id = op.Id;
        standardPrice.UnitPrice = 100;
        standardPrice.IsActive = true;
        standardPrice.UseStandardPrice = false;
        insert standardPrice;
                
        Contract cont = new Contract();
        cont.AccountId= acc.id;
        cont.StartDate=date.today();
        cont.ContractTerm=2;
        cont.Status='Draft';
        cont.Next_Order_Date__c = Date.today();
        cont.Pricebook2Id = standardPricebook.Id;
        cont.Service__c = op.Id;
        //cont.Insurance__c = mp.Id;
        cont.BillingStreet = 'test';
        cont.BillingPostalCode = '759128';
        cont.BillingState = 'test';
        cont.BillingCity = 'test';
        cont.BillingCountry = 'test';
        cont.BillingLatitude = 20.296059;
        cont.BillingLongitude = 85.824539;
        cont.ShippingCity = 'test';
        cont.ShippingCountry = 'test';
        cont.ShippingPostalCode = '777777';
        cont.ShippingLatitude = 20.296059;
        cont.ShippingLongitude = 85.824539;
        cont.Insurance__c = 'Medicaid';
        cont.Insurance_Provider__c = 'Medicaid';
        cont.Group_ID__c = '1234GID';
        cont.Policy_ID__c = 'PID1234';
        cont.Policy_Holder_First_Name__c = 'Test';
        cont.Policy_Holder_Last_Name__c = 'Test';
        //cont.Service__c = op.Id;
        insert cont;
                
        Order o = new Order();
        o.AccountId = acc.Id;
        o.ContractId = cont.Id;
        o.Status = 'Draft';
        o.EffectiveDate = system.today();
        o.BillToContactId = con.Id;
        o.ShipToContactId = con.Id;
        o.Insurance__c = cont.Insurance__c;
        o.Insurance_Name__c = cont.Insurance_Provider__c;
        o.Insurance_ID__c = cont.Policy_ID__c;
        o.Insurance_Group_Number__c = cont.Group_ID__c;
        insert o;
                
        OrderItem oi = new OrderItem();
        oi.sstation__Currency_Type__c = 'USD';
        oi.OrderId = o.Id;
        oi.Quantity = 20.4;
        oi.UnitPrice = 100;
        oi.PricebookEntryId = standardPrice.Id;
        insert oi;
                
        Contract contr = new Contract();
        contr.Status = 'Activated';
        contr.Id = cont.Id;
        contr.Next_Order_Date__c = date.today()+3;
        update contr;
                
                {
            Order od = new Order(
                AccountId = acc.Id,
                ContractId = cont.Id,
                EffectiveDate = System.today(),
                Status = 'Draft',
                BillToContactId = con.Id,
                ShipToContactId = con.Id,
                PriceBook2Id = Test.getStandardPricebookId()  
            );
            System.assert(True, 'ErrorMessage');
            
             }
                
        Test.startTest();
        AutoSubscriptionForOrderCreation obj = new AutoSubscriptionForOrderCreation();
        String CRON_EXP = '0 0 0 3 9 ? 2042';
        system.schedule('Test status Check9', CRON_EXP, obj );
        Test.stopTest();
 
}
}

When am removing this two line coverage is 91% but when i am including this two line thne coverage is 60%
orderObj.ShipToContactId = con.account.PersonContactId;
orderObj.BillToContactId = con.account.PersonContactId;

SubratSubrat (Salesforce Developers) 
Hello Sudeep ,

In order to achieve a higher code coverage, it would be necessary to write additional test methods that test the different scenarios that the batch class could encounter, such as:

1). The scenario where there are no Contracts that meet the criteria of the batch class.
2). The scenario where the Contract object is missing required fields or contains incorrect values.
3). The scenario where the batch class has to create multiple Orders for a single Contract.
4). The scenario where the batch class has to handle exceptions during the execution of the execute method.

Reference -> https://salesforce.stackexchange.com/questions/244788/how-do-i-write-an-apex-unit-test

Hope the above information helps !
Thank you.