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
Laetitia Damen 9Laetitia Damen 9 

How do write test class for batch class ?

Hi there! 

I'm looking to write a class test for my batch. Any advice? 
 
global class FA_BA_UpdateAccounts implements Database.Batchable<sObject>{
    
   global Database.QueryLocator start(Database.BatchableContext info){ 
       //Requeter seulement les comptes qui ont au moins une commande avec le Status 'Ordered'
       return Database.getQueryLocator('SELECT Id FROM Account WHERE Id In =: (SELECT AccountId FROM Order WHERE Status = \'Ordered\' AND Status = \'Activated\' )');
       
       //new instance of accountQuery
       //FA_QR_Account accountQuery = new FA_QR_Account();
   }
    
   global void execute(Database.BatchableContext info, List<Account> scope){      
    
    FA_QR_Order orderQuery = new FA_QR_Order();     
    
    FA_SRV_Account accountService = new FA_SRV_Account();

    //Call the method getOrders   
    list<Order> listOrders =  orderQuery.getOrders();
       
		for(integer i=0; i < scope.size(); i++){
			Account myAccount = scope[i];
			myAccount.Chiffre_d_affaire__c = 0;
           for(integer j=0; j < listOrders.size(); j++){
               if(listOrders[j].AccountId == myAccount.Id){
                   myAccount.Chiffre_d_affaire__c = myAccount.Chiffre_d_affaire__c + listOrders[j].TotalAmount;
               }                   
           }
       }
       
       
       accountService.updateAccount(scope);

   }    
    
   global void finish(Database.BatchableContext info){     
       
   } 
}

 
AbhinavAbhinav (Salesforce Developers) 
Check this:

https://jayakrishnasfdc.wordpress.com/2021/01/02/apex-test-class-for-batch-apex/

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

https://salesforce.stackexchange.com/questions/244794/how-do-i-increase-my-code-coverage-or-why-cant-i-cover-these-lines

If you face any specific issue while attempting do post that here.

Thanks!
Laetitia Damen 9Laetitia Damen 9
Hi Abhinav, 

Thanks for your reply. I've attempted some issues with the order status: 
= >first error: FAILED_ACTIVATION, Choose a valid status and save your changes. For a new or cloned order, choose Draft. An Activated order's status can't be edited.: [Status]
I'm looking for setting up my test with the status "Ordered" :
 
isTest
private class TestBAUpdateAccount {

    @testSetup
    static void setUp() 
    {
        
        List<Account> accounts = new List<Account>();
        List<Order> listOrders= new List<Order>();
        // insert 10 accounts
        for (Integer i=0;i<10;i++) {
            accounts.add(new Account(name='Account '+i,
            chiffre_d_affaire__c= 20000 ));
        }
        insert accounts;
        // find the account just inserted. add order for each
        for (Account account : [select id from account]) {
            listOrders.add(new Order( 
            Status= 'Ordered',
            accountId=account.id ));
        }
        insert listOrders;
    }
    @isTest static void test() {
        Test.startTest();
        FA_BA_UpdateAccounts uac = new FA_BA_UpdateAccounts();
        Id batchId = Database.executeBatch(uac);
        Test.stopTest();

        // after the testing stops, assert records were updated properly
        System.assertEquals(10, [select count() from order where Status = 'Ordered']);

        
    }
}

 
CharuDuttCharuDutt
Hii Leatitia
Try Below Test Class
@isTest
public Class TestBAUpdateAccount {
@isTest
public Static Void UnitTest(){
Product2 p = new Product2();
p.Name = 'Test Product';
p.Description='Test Product';
p.productCode = 'ABC';
p.isActive = true;
insert p;

PricebookEntry standardPrice = new PricebookEntry();
standardPrice.Pricebook2Id = Test.getStandardPricebookId();
standardPrice.Product2Id = p.Id;
standardPrice.UnitPrice = 100;
standardPrice.IsActive = true;
standardPrice.UseStandardPrice = false;
insert standardPrice ;

Account acc = new Account(
Name = 'Test Account',
);
insert acc;

Order order = new Order(
AccountId = acc.Id,
EffectiveDate = System.today(),
Status = 'Draft',
PriceBook2Id = Test.getStandardPricebookId()
);
insert order;
OrderItem lineItem = new OrderItem();
lineItem.OrderId = order.id;
lineItem.Quantity = 24;
lineItem.UnitPrice = 240;
lineItem.Product2id = p.id;
lineItem.PricebookEntryId=standardPrice.id;
insert lineItem;

order.Status = 'Activated';
update order;

  Test.startTest(); 
FA_BA_UpdateAccounts uac = new FA_BA_UpdateAccounts(); 
Id batchId = Database.executeBatch(uac);
 Test.stopTest();
}
}
Please Mark It As Best Answer If  It Helps
Thank You!