-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathAsynchronous Apex-Use Batch Apex
68 lines (56 loc) · 2.71 KB
/
Asynchronous Apex-Use Batch Apex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
Challenge 8:
Create an Apex class that uses Batch Apex to update Lead records.
Create an Apex class that implements the Database.Batchable interface to update all Lead records in the org with a specific LeadSource. Write unit tests that achieve 100% code coverage for the class.
Create an Apex class called 'LeadProcessor' that uses the Database.Batchable interface.
Use a QueryLocator in the start method to collect all Lead records in the org.
The execute method must update all Lead records in the org with the LeadSource value of 'Dreamforce'.
Create an Apex test class called 'LeadProcessorTest'.
In the test class, insert 200 Lead records, execute the 'LeadProcessor' Batch class and test that all Lead records were updated correctly.
The unit tests must cover all lines of code included in the LeadProcessor class, resulting in 100% code coverage.
Run your test class at least once (via 'Run All' tests the Developer Console) before attempting to verify this challenge.
Solution:
1.LeadProcessor.apxc
global class LeadProcessor implements Database.Batchable<sObject>, Database.Stateful {
global Integer leadsProcessed = 0;
global Database.QueryLocator start(Database.BatchableContext bc){
return Database.getQueryLocator('select id, lastname ,status, company from Lead');
}
global void execute(Database.BatchableContext bc, List<Lead> allLeads){
List<Lead> leads = new List<Lead>();
for(Lead l: allLeads){
l.LeadSource='Dreamforce';
}
update leads;
}
global void finish(Database.BatchableContext bc){
System.debug(leadsProcessed + ' leads processed. Nigga!');
AsyncApexJob job = [SELECT Id, Status, NumberOfErrors,
JobItemsProcessed,
TotalJobItems, CreatedBy.Email
FROM AsyncApexJob
WHERE Id = :bc.getJobId()];
EmailManager.sendMail('jgatsby1996@gmail.com','Total Leads Porcessed are ',' '+leadsProcessed);
}
}
2.LeadProcessorTest
@isTest
public class LeadProcessorTest {
@testSetup
static void setup(){
List<Lead> leads = new List<Lead>();
for (Integer i=0;i<200;i++) {
leads.add(new Lead(Lastname='Last '+i,
status='Open - Not Contacted'
, company='LeadCompany'+i));
}
insert leads;
}
static testmethod void test() {
Test.startTest();
LeadProcessor lp = new LeadProcessor();
Id batchId = Database.executeBatch(lp);
Test.stopTest();
// after the testing stops, assert records were updated properly
System.assertEquals(200, [select count() from Lead where LeadSource = 'Dreamforce']);
}
}