I'm writing a batch class in Apex, and I want to properly cover the scenario where AsyncApexJob.NumberOfErrors > 0
.
In my batch class, I check for errors in the finish
method like this:
public void finish(Database.BatchableContext BC) {
AsyncApexJob job = [
SELECT
Id
, Status
, NumberOfErrors
, TotalJobItems
FROM AsyncApexJob
WHERE Id = :BC.getJobId()
];
if (job.NumberOfErrors > 0) {
System.debug('Batch failed with errors.');
// Todo somthing
} else {
System.debug('Batch completed successfully.');
// Todo somthing
}
}
My questions:
- In which scenarios does
AsyncApexJob.NumberOfErrors
become greater than zero? - How can I properly write a
test class
to cover this case?
From my research, NumberOfErrors
increases when an unhandled exception occurs inside the execute
method. However, when testing, I cannot directly control AsyncApexJob
, and it seems NumberOfErrors
is always 0
in tests.
Here is a simplified version of my batch class:
global class MyBatchClass implements Database.Batchable<sObject> {
public Database.QueryLocator start(Database.BatchableContext BC) {
return Database.getQueryLocator([SELECT Id FROM Account]);
}
public void execute(Database.BatchableContext BC, List<Account> scope) {
delete scope;
}
public void finish(Database.BatchableContext BC) {
AsyncApexJob job = [
SELECT
Id
, Status
, NumberOfErrors
, TotalJobItems
FROM AsyncApexJob
WHERE Id = :BC.getJobId()
];
if (job.NumberOfErrors > 0) {
System.debug('Batch failed with errors.');
// Todo somthing
} else {
System.debug('Batch completed successfully.');
// Todo somthing
}
}
}
Thanks!