1

I have a Batch Class

global class UpdateAssetInstallStatus implements Database.Batchable<sObject> {
    global Integer assetsProcessed = 0;

    global Database.QueryLocator start(Database.BatchableContext bc) {
        return Database.getQueryLocator([SELECT Name,InstallDate FROM Asset WHERE InstallDate <= TODAY]);
    }

    global void execute(Database.BatchableContext bc, List<Asset> scope){
        // process each batch of records
        for (Asset asset : scope) {
            asset.Status = 'Installed';
            assetsProcessed = assetsProcessed + 1;
        }
        update scope;
    }
    global void finish(Database.BatchableContext bc) {
        System.debug(assetsProcessed + ' records processed.');
    }
}

that is triggered by a Scheduled Class (through

global class ScheduleUpdateAssetInstallStatus implements Schedulable {
    // Run daily at 10AM
    public static String CRON_EXP = '0 0 10 * * ? *';

    global static String scheduleAssetUpdate() {
        ScheduleUpdateAssetInstallStatus sc = new ScheduleUpdateAssetInstallStatus();
        return System.schedule('Asset Install Status Update', CRON_EXP, sc);
    }

    global void execute(SchedulableContext ctx) {
        UpdateAssetInstallStatus batchJob = new UpdateAssetInstallStatus();
        Database.executeBatch(batchJob);
    }
}

Is it necessary to write two separate test classes for these or is it possible to do it in one? Is it recommended to do two separate ones? To achieve 100% code coverage I have to insert the same dummy data in both, rather than just the Batch Class.

1
  • As long as your code is covered, you can create only one test class to test. It's more of a choice how you want to maintain your unit tests.
    – Jayant Das
    Commented Aug 8, 2018 at 17:45

1 Answer 1

3

No, it is not necessary. There is some common convention that a class called Xyz should have a test class called XyzTest, but it's not necessary that this is so. I recommend always using this pattern to make the tests easy to find.

Also, I might mention it's possible to have a scheduled interface and batchable interface in the same class. This is preferable when the only purpose of the scheduled class is to call the batchable class. This also allows you to combine the unit tests for both into a single class, resulting in two classes instead of four, while maintaining the ability to find the tests when you need to.


public class Xyz implements Schedulable, Database.Batchable<sObject> {
  public void execute(SchedulableContext context) {
    Database.executeBatch(this);
  }
  public Database.QueryLocator start(Database.BatchableContext context) {
    ...
  }
  ...
}

@isTest class XyzTest {
  @testSetup static void createData() {
    ...
  }
  @isTest static void testScheduler() {
    ...
  }
  @isTest static void testBatchable() {
    ...
  }
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .