function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Daniel Steven Ospina PinedaDaniel Steven Ospina Pineda 

Help with Create an Apex class that uses the @future annotation to update Account records.

Hi guys, so I am trying to check this traihead but for some reason the challengue check is not working. Error messageI have already tried to delete the custom field and create it again, tried creating a new playground for the challenge but i am getting the same error over and over. I have the same code that the video shows in the trailhead so that should not be  the problem either. Has someone encounter this issue? 

User-added image
ravi soniravi soni
hi,
here is main class and test class. you just need to copy and paste.
public class AccountProcessor {
@future
    public static void countContacts(list<Id> lstAccId){
        list<Account> lstAccount = new list<Account>();
        for(Account acc : [SELECT Id,Name,Number_of_Contacts__c,(SELECT Id FROM Contacts) FROM Account WHERE Id In :lstAccId]){
            acc.Number_of_Contacts__c = acc.contacts.size();
            lstAccount.add(acc);
        }
        if(lstAccount.size() > 0){
            update lstAccount;
        }
     }
}

//Test class
@isTest
public class AccountProcessorTest {
@isTest
    public static void testCountContacts(){
        list<Account> lstAccount = new list<Account>();
        list<contact> lstContact = new list<Contact>();
        list<Id> lstAccId = new list<Id>();
        
        for(integer i=0; i<5; i++){
            Account acc = new Account();
            acc.Name = 'Test ' + i;
        lstAccount.add(acc);
        }
        if(lstAccount.size() > 0){
            insert lstAccount;
        }
        for(Account oAcc : lstAccount){
            contact con = new contact();
            con.LastName = oAcc.Name + '-contact';
            con.AccountId = oAcc.Id;
            lstContact.add(con);
            lstAccId.add(oAcc.Id);
        }
        if(lstContact.size() > 0){
            insert lstContact;
        }
        Test.startTest();
        AccountProcessor.countContacts(lstAccId);
        Test.stopTest();
        Account acc = [SELECT Id,Name,Number_of_Contacts__c FROM Account WHERE Name = 'Test 1' limit 1];
        system.assertEquals(1,acc.Number_of_Contacts__c );
        
    }
}

let me know if it helps you by marking it as best answer.
Thank you
ravi soniravi soni
hi  Daniel,
did you try my code. I believe you will achieve your requirment by using my solution.
don't forget to mark it as best answer.
thank you