public class AccountProcessor {
@future
public static void countContacts(List<Id> accountIds) {
List<Account> accounts = [Select Id, Name from Account Where Id IN :accountIds];
// process account records to do awesome stuff
List<Contact> con = [select id from contact where AccountId in :accounts];
for(Account a : accounts){
a.Number_Of_Contacts__c=con.size();
}
}
}
Name: AccountProcessorMethod name: countContactsThe method must accept a List of Account IDsThe method must use the @future annotationThe method counts the number of Contact records associated to each Account ID passed to the method and updates the 'Number_Of_Contacts__c' field with this valueCreate an Apex test class:Name: AccountProcessorTestThe unit tests must cover all lines of code included in the AccountProcessor class, resulting in 100% code coverage.Before verifying this challenge, run your test class at least once using the Developer Console Run All feature@isTest
public class AccountProcessorTest {
public static testmethod void TestAccountProcessorTest() {
Account a= new Account ();
a.Name='Test Account';
Insert a;
Contact cont=New Contact();
cont.FirstName='Bob';
cont.LastName='Masters';
cont.AccountId=a.ID;
Insert cont;
List<Id> setAccId = new List<ID>();
setAccId.add(a.id);
Test.startTest();
AccountProcessor.countContacts(setAccId);
Test.stopTest();
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);
}
}
Just discovered that there was an exception which said that the insert was not successful and then I tried to do a manual insertion from the UI and then realized there was a validation rule which was preventing creation of a new account. After deactivating that it was successful.