-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathAsynchronous Apex-Use Future Methods
51 lines (43 loc) · 2.26 KB
/
Asynchronous Apex-Use Future Methods
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
Challenge 7:
Create an Apex class that uses the @future annotation to update Account records.
Create an Apex class with a method using the @future annotation that accepts a List of Account IDs and updates a custom field on the Account object with the number of contacts associated to the Account. Write unit tests that achieve 100% code coverage for the class.
Create a field on the Account object called 'Number_of_Contacts__c' of type Number. This field will hold the total number of Contacts for the Account.
Create an Apex class called 'AccountProcessor' that contains a 'countContacts' method that accepts a List of Account IDs. This method must use the @future annotation.
For each Account ID passed to the method, count the number of Contact records associated to it and update the 'Number_of_Contacts__c' field with this value.
Create an Apex test class called 'AccountProcessorTest'.
The unit tests must cover all lines of code included in the AccountProcessor 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.AccountProcessor.apxc
public class AccountProcessor {
@future
public static void countContacts(Set<Id> setId){
List<Account> lstAccount = [select Id,Number_of_Contacts__c,(select id from contacts) from account where id in :setId];
for(Account acc : lstAccount){
List<Contact> lstCont = acc.contacts;
acc.Number_of_Contacts__c = lstCont.size();
}
update lstAccount;
}
}
2.AccountProcessorTest.apxc
@isTest
public class AccountProcessorTest {
public static testMethod void testAccountProcessorTest(){
Test.startTest();
Account a = new Account();
a.Name = 'The Pirates';
insert a;
Contact cont = new Contact();
cont.FirstName ='jack';
cont.LastName ='Sparrow';
cont.AccountId = a.Id;
insert cont;
Set<Id> setAccId = new Set<ID>();
setAccId.add(a.Id);
AccountProcessor.countContact(setAccId);
Account acc = [select Number_of_Contacts__c from Account where id = :a.id LIMIT 1];
System.assertEquals(Integer.valueOf(acc.Number_of_Contacts__c) ,1);
Test.stopTest();
}
}