ApexSensei

Drills Debugging

Fix a Batch job that forgets its count

Each execute and finish runs in its own transaction on a fresh copy of the class.

Your task

Fix the Batch so finish reports the number of Opportunities execute archived.

public class AS_E79CBE2A337D_ArchiveBatch implements Database.Batchable<SObject> {
    private Set<Id> opportunityIds;
    private Integer archivedCount = 0;

    public AS_E79CBE2A337D_ArchiveBatch(Set<Id> opportunityIds) {
        this.opportunityIds = opportunityIds;
    }

    public Database.QueryLocator start(Database.BatchableContext context) {
        return Database.getQueryLocator([
            SELECT Id
            FROM Opportunity
            WHERE Id IN :opportunityIds AND IsClosed = true
        ]);
    }

    public void execute(Database.BatchableContext context, List<SObject> scope) {
        List<Opportunity> updates = new List<Opportunity>();
        for (SObject item : scope) {
            Opportunity opportunity = (Opportunity) item;
            opportunity.Description = 'Archived';
            updates.add(opportunity);
        }
        update updates;
        archivedCount += updates.size();
    }

    public void finish(Database.BatchableContext context) {
        insert new Task(Subject = 'Archived ' + archivedCount + ' opportunities');
    }
}

Requirements

  1. archivesClosedOpportunities should pass
  2. leavesOpenOpportunitiesAlone should pass
  3. reportsTheCountInFinish should pass
  4. reportsZeroWhenNothingIsClosed should pass
  5. keepsEachJobsCountSeparate should pass

Sign in to open this drill