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
Jon GradmanJon Gradman 

batch apex test class help

Hi all,

I've been a Salesforce admin for 2 years and have experience with point and click development like Visual Workflow and Visualforce controllers but I don't have a lot of experience writing test classes.  This test class is coming up short with 43% coverage:
 
@isTest
private class AcctUpdateTest {
    
  public static testMethod void testschedule() {

  Test.StartTest();
  AccountsUpdate sh1 = new AccountsUpdate();      
    String sch = '0 0 23 * * ?';
        system.schedule('Test check', sch, sh1);
    Test.stopTest();
 
    }
}

Here is the class code.  The reason I am updating the code is to avoid being timed out by a trigger, which is part of the Lookup Helper managed package.  Our batchable APEX code below runs every night to update all of our customer Accounts in SFDC so that various workflows and alerts fire when they are relevant.  Since installing this package, however, we are having timeout errors.  As a second question, will this code help increase the CPU time to avoid an error?
 
global class AccountsUpdate implements Database.Batchable<sObject>,Schedulable {
    global Database.QueryLocator start(Database.BatchableContext bc) {
        String query = 'SELECT Id, Type FROM Account'; // create the query to run
        return Database.getQueryLocator(query); //get all of the data in the start
    }
    global void execute(Database.BatchableContext bc,List<sObject> objects){
        //because a generic list is passed in, you have to 'box' it (type set) it to the Right Object.
        List<Account> acctList = [Select Id, Type From Account Where Type = 'Customer - Current' OR Type =               'Customer - Current - Overdue' ];
        List<Account> updAccounts = new List<Account>();
        integer counter = 0;
        
        for(Account thisAcct : acctList) {
            updAccounts.add(thisAcct);
            counter++;
            if (counter == 20) { update(updAccounts); }
        }
        
        if (counter > 0) { update(updAccounts); }
    }
    global void finish(Database.BatchableContext BC) {
        AsyncApexJob aaj = [Select Id, Status, NumberOfErrors, JobItemsProcessed, MethodName, TotalJobItems, CreatedBy.Email from AsyncApexJob where Id =:BC.getJobId()];
    }
    global void execute(SchedulableContext sc){
        Database.executeBatch(new AccountsUpdate());
    }
}
The old code just selected all customers and attempted an update, but doing 200 records at a time was making the triggers associated with Lookup Helper to fail / timeout - since they are written for every update on Accounts and not for specific fields.

Any suggestions?  All help appreciated thank you.

- Jon
 
Best Answer chosen by Jon Gradman
Raj VakatiRaj Vakati
Try this code 
 
@isTest
private class AccountsUpdateTest {
    @testSetup 
    static void setup() {
        List<Account> accounts = new List<Account>();
        List<Contact> contacts = new List<Contact>();
        // insert 10 accounts
        for (Integer i=0;i<10;i++) {
            accounts.add(new Account(name='Account '+i, 
                billingcity='New York', billingcountry='USA'));
        }
        insert accounts;
        // find the account just inserted. add contact for each
        for (Account account : [select id from account]) {
            contacts.add(new Contact(firstname='first', 
                lastname='last', accountId=account.id));
        }
        insert contacts;
    }
    static testmethod void test() {        
        Test.startTest();
        AccountsUpdate  uca = new AccountsUpdate ();
        Id batchId = Database.executeBatch(uca);
        Test.stopTest();
        
    }
    
	
	static testmethod void test() {        
        Test.StartTest();
  AccountsUpdate sh1 = new AccountsUpdate();      
    String sch = '0 0 23 * * ?';
        system.schedule('Test check', sch, sh1);
    Test.stopTest();
      
    }
}

 

All Answers

Jon GradmanJon Gradman
^ decrease CPU time so it doesn't fail
Raj VakatiRaj Vakati
Try this code 
 
@isTest
private class AccountsUpdateTest {
    @testSetup 
    static void setup() {
        List<Account> accounts = new List<Account>();
        List<Contact> contacts = new List<Contact>();
        // insert 10 accounts
        for (Integer i=0;i<10;i++) {
            accounts.add(new Account(name='Account '+i, 
                billingcity='New York', billingcountry='USA'));
        }
        insert accounts;
        // find the account just inserted. add contact for each
        for (Account account : [select id from account]) {
            contacts.add(new Contact(firstname='first', 
                lastname='last', accountId=account.id));
        }
        insert contacts;
    }
    static testmethod void test() {        
        Test.startTest();
        AccountsUpdate  uca = new AccountsUpdate ();
        Id batchId = Database.executeBatch(uca);
        Test.stopTest();
        
    }
    
	
	static testmethod void test() {        
        Test.StartTest();
  AccountsUpdate sh1 = new AccountsUpdate();      
    String sch = '0 0 23 * * ?';
        system.schedule('Test check', sch, sh1);
    Test.stopTest();
      
    }
}

 
This was selected as the best answer
Jon GradmanJon Gradman
This was the final code, based on your code (yours didn't run because of some custom configs on our side, and I changed it a little to avoid methods being called the same thing or the names of objects):
 
@isTest
private class AcctUpdateTest {
    @testSetup 
    static void setup() {
        List<Account> newAccts = new List<Account>();
        List<Contact> newCntcs = new List<Contact>();
        // insert 10 accounts
        for (Integer i=0;i<10;i++) {
            newAccts.add(new Account(name='Account '+i, 
                billingcity='New York', billingcountry='United States', website='na'+i+'.com'));
        }
        insert newAccts;
        // find the account just inserted. add contact for each
        for (Account acc : [select id from account]) {
            newCntcs.add(new Contact(firstname='first', 
                lastname='last', accountId=acc.id));
        }
        insert newCntcs;
    }
    static testmethod void test() {        
        Test.startTest();
        AccountsUpdate  uca = new AccountsUpdate ();
        Id batchId = Database.executeBatch(uca);
        Test.stopTest();
        
    }
    
    
    static testmethod void test2() {        
        Test.StartTest();
  AccountsUpdate sh1 = new AccountsUpdate();      
    String sch = '0 0 23 * * ?';
        system.schedule('Test check', sch, sh1);
    Test.stopTest();
      
    }
}