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
Glenn Dailey 1Glenn Dailey 1 

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

The 'AccountProcessor' class did not achieve 100% code coverage via your test methods. Make sure that you chose 'Run All' tests in the Developer Console at least once before attempting to verify this challenge. I did the run all with no luck. I did notice that this is the new section that was just added and I ran into issues in the first unit too.

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.

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;
  }
}

and
@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;
       
        set<Id> setAccId = new Set<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);
  }
 
}
Best Answer chosen by Glenn Dailey 1
Amit Chaudhary 8Amit Chaudhary 8
I am glad that works. PLease mark best answer and close this thread so that if some one has same issue that post can help other

All Answers

Amit Chaudhary 8Amit Chaudhary 8
Please check below post similer issue
1) https://developer.salesforce.com/forums/?id=906F0000000D8hwIAC
2) https://developer.salesforce.com/forums/?id=906F0000000DDdQIAW

Your Code look good to me.

NOTE:- Before checking the challange you need to click on Run Test Button on top of Test class. Once Test class execution will over then check code coverage. Then check your challange

Let us know if this will help you

Thanks
Amit Chaudhary
Glenn Dailey 1Glenn Dailey 1
I did the test getting the following
System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, AccountDeletion: execution of BeforeInsert

caused by: System.NullPointerException: Attempt to de-reference a null object

External entry point: []
Amit Chaudhary 8Amit Chaudhary 8
It look like you have any "AccountDeletion" Trigger on Account object which is failing. Can you please deactivate the same trigger and try above code again.
Please follow below steo:-

1) Please deactivate trigger "AccountDeletion"
2) Execute Test Class again
3) Check your challange

Let us know if this will help you

 
Glenn Dailey 1Glenn Dailey 1
Yes that worked Thank you Amit
Amit Chaudhary 8Amit Chaudhary 8
I am glad that works. PLease mark best answer and close this thread so that if some one has same issue that post can help other
This was selected as the best answer
Nitesh Acharya 19Nitesh Acharya 19
The AccountProcesser can be modified slightly
public class AccountProcessor {
    @future
    public static void countContacts(set<ID> Accnts){
        List<Account> acc = [select Name from Account where Id IN :accnts];
        List<Account> xyz = new List<Account>();
        for(Account a:acc){
            a.Number_of_Contacts__c = [select Count() from Contact where AccountId =:a.Id];
            xyz.add(a);
        }
        update xyz;
    }
}



Test Class
@isTest
public class AccountProcessorTest {
    @isTest public static void accnt(){
        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;
   
        Set<Id> setAccId = new Set<ID>();
        setAccId.add(a.id);
        
        Test.startTest();
        AccountProcessor.countContacts(setAccId);
        Test.stopTest();
    }
}
Vishal_SharmaVishal_Sharma

What is the purppose of  (Set<id> setId) in

 public static void countContacts(Set<id> setId) Statement ?

Myrna LoveMyrna Love
Denise Love
I've tried everything I can think of at least 3 times and I still get the error message:
Challenge not yet complete... here's what's wrong:
The Apex class does not appear using the '@future' annotation.
What am I missing, please.
Robin Bansal 35Robin Bansal 35
Below solution worked for me:
public class AccountProcessor {
    @future
    public static void countContacts(List<Id> accountIds){
        List<Account> accounts = [Select Id, Name from Account Where Id IN : accountIds];
        List<Account> updatedAccounts = new List<Account>();
        for(Account account : accounts){
           account.Number_of_Contacts__c = [Select count() from Contact Where AccountId =: account.Id];
            System.debug('No Of Contacts = ' + account.Number_of_Contacts__c);
            updatedAccounts.add(account);
        }
        update updatedAccounts;
    }

}

Test class:
@isTest
public class AccountProcessorTest {
    @isTest
    public static void testNoOfContacts(){
        Account a = new Account();
        a.Name = 'Test Account';
        Insert a;
        
        Contact c = new Contact();
        c.FirstName = 'Bob';
        c.LastName =  'Willie';
        c.AccountId = a.Id;
        
        Contact c2 = new Contact();
        c2.FirstName = 'Tom';
        c2.LastName = 'Cruise';
        c2.AccountId = a.Id;
        
        List<Id> acctIds = new List<Id>();
        acctIds.add(a.Id);
        
        Test.startTest();
        AccountProcessor.countContacts(acctIds);
        Test.stopTest();
    }

}
Ronak BansalRonak Bansal
@istest 
public class AccountProcessorTest
{
    @istest
    public static void test()
    {
        account a=new account();
        a.name='reddy;
        a.emp_name__c='john';
        insert a;
        
        contact c=new contact();
        c.lastname='jjen';
        c.accountid=a.id;
*************error********************
        insert c;
*************error********************

        
        list<id> x=new list<id>();
        x.add(a.id);
           
        test.startTest();
        AccountProcessor.countContacts(x);
        test.stopTest();
        
        
    }
        
}


It is showing error in the statement " insert c "
please tell me why?

 
Rehan AhmedRehan Ahmed
Hi Amit, There is issue while running the test, Assertion failure is occuring,  

At this line :

System.assertEquals ( Integer.valueOf(ACC.Number_of_Contacts__c) ,1);

Error details:

System.AssertException: Assertion Failed: Expected: 2, Actual: 1

 
anuroop sudanagunta 7anuroop sudanagunta 7
Apex Class:

public class AccountProcessor {
    @future
    public static void CountContacts(Set<Id> Acctid){
        List<Account> AccList = [select id , number_of_contacts__c ,(Select id from Contacts) From Account where id In :Acctid];
       List<Account> updtLst = new List<Account>();
        for(Account a :AccList){
            a.Number_of_Contacts__c = a.contacts.size();
             UpdtLst.add(a);
        }
        Update updtLst;
    }
}

Test Class:

@isTest
public class AccountProcessorTest {
@isTest
    static void countContactsTest(){
        Account a = new Account(Name='Test');
             insert a;
        Contact c = new Contact(FirstName='testing',LastName='Test',Accountid=a.id);
             insert c;
        Contact cn = new Contact(FirstName='Nice',LastName='Test',AccountId = a.id);
             insert cn;
       list<Account> accList = [select id ,Number_of_Contacts__C,(Select id from Contacts) From Account where id = :a.Id ];
       set <Id> nlist = new set <Id>();
        for(Account at :accList){
          nlist.add(at.id);
        }
        test.startTest();
        AccountProcessor.CountContacts(nlist);
        test.stopTest();
        Account aCnt = [Select id , Number_of_Contacts__c from Account];
       system.assertEquals(2,aCnt.Number_of_Contacts__c); 

    }
}

 
ajay singh 167ajay singh 167
public class AccountProcessor {
    @future
    public static void countContacts(List<Id> accountIds){
        List<Account> accounts = [Select Id, Name from Account Where Id IN : accountIds];
        List<Account> updatedAccounts = new List<Account>();
        for(Account account : accounts){
           account.Number_of_Contacts__c = [Select count() from Contact Where AccountId =: account.Id];
            System.debug('No Of Contacts = ' + account.Number_of_Contacts__c);
            updatedAccounts.add(account);
        }
        update updatedAccounts;
    }

}

@IsTest
-------------Error----------------
Missing" " at'@'
---------------------------------------
public class AccountProcessorTest {
    @IsTest
    public static void testNoOfContacts(){
        Account a = new Account();
        a.Name = 'Test Account';
        Insert a;
        
        Contact c = new Contact();
        c.FirstName = 'Bob';
        c.LastName =  'Willie';
        c.AccountId = a.Id;
        
        Contact c2 = new Contact();
        c2.FirstName = 'Tom';
        c2.LastName = 'Cruise';
        c2.AccountId = a.Id;
        
        List<Id> acctIds = new List<Id>();
        acctIds.add(a.Id);
        
        Test.startTest();
       
        Test.stopTest();
    }

}

 
Ahmed Nawaz 14Ahmed Nawaz 14
Thanks for info You Like to Read Happy New Year 2020 (http://https://happynewyearcraze.com" target="_blank)
 
Alex sandro 1Alex sandro 1
It's a helpful article for update Account record. Thanks. If you like to know all kind of apk files, tamilrockers new link join us(bdtechsupport (https://bdtechsupport.com))
Gaurav Gupta 199Gaurav Gupta 199
It's worked for me. You can refer below code:

public class AccountProcessor{
    @future
    public static void countContacts(List<Id> accountIds){
        List<Account> vAccountList = new List<Account>();
        List<Account> acc = [SELECT Id,Name,
                             (SELECT Id,Name FROM Contacts) 
                             FROM Account WHERE Id IN :accountIds];
        System.debug('total contact in Account: ' + acc);
        
        if(acc.size() > 0){
            for(Account a: acc){
                List<Contact> con = [SELECT Id,Name FROM Contact WHERE accountId = :a.Id];
                a.Number_of_Contacts__c = con.size();
                vAccountList.add(a);
            }
            if(vAccountList.size()>0)
            {
                update vAccountList;
            }
        }
    }
}

Test Class:
==================
@isTest
public class AccountProcessorTest {
    @isTest public static void testNoOfContacts(){
        Account a = new Account(Name = 'Acme1');
        Insert a;
        Account b = new Account(Name = 'Acme2');
        insert b;
        Contact c = new Contact(FirstName = 'Gk', LastName = 'Gupta', accountId = a.Id);
        insert c;
        Contact c1 = new Contact(FirstName = 'Gk1', LastName = 'Gupta1', accountId = b.Id);
        insert c1;
        
        List<account> acnt = [SELECT Id FROM Account WHERE Name = :a.Name OR Name = :b.Name];
        System.debug('size of acnt: ' + acnt);
        List<ID> acntIDLST = new List<Id>();
        for(Account ac: acnt){
            acntIDLST.add(ac.Id);
        }
        Test.startTest();
        AccountProcessor.countContacts(acntIDLST);
        Test.stopTest();
    }
}
Mykola Hlynka 30Mykola Hlynka 30
// Class AccountProcess

global class AccountProcessor {
    @future
    public static void countContacts(Set<Id> AccoundIds){
        List<Account> ListAccounts = [SELECT Id, Name, Number_of_Contacts__c, (SELECT Id FROM Contacts) FROM Account WHERE id in :AccoundIds];
        
        
        for(Account acc: ListAccounts)
        {
            List<Contact> Con = acc.Contacts;
            
            if(!Con.isEmpty())
            {
                acc.Number_of_Contacts__c = Con.size();
            }
            else
            {
                
                acc.Number_of_Contacts__c = 0;
            }
            
        }
        update ListAccounts;
    }
    
    
}





//Class AccountProcessTEST

@IsTest
private class AccountProcessorTest {
    @IsTest
    private static void TestContactNumber(){
        Account a = new Account();
      			a.Name = 'Brasil Test';
       	 Insert a;
        
        Account b = new Account();
                b.Name = 'France Test';
         Insert b;
        
        Contact cont = New Contact();
        cont.FirstName = 'Roberto';
        cont.LastName = 'Carlos';
        cont.AccountId = a.Id;
        Insert cont;
        
        set<Id> setAccId = new Set<Id>();
        setAccId.add(a.id);
        setAccId.add(b.id);
          
        Test.startTest();
            AccountProcessor.countContacts(setAccId);
        Test.stopTest();
        
       Account ACC = [select Number_of_Contacts__c from Account where id = :a.id LIMIT 1];
       System.debug(ACC);
       System.assertEquals ( Integer.valueOf(ACC.Number_of_Contacts__c) ,1);
        ACC = [select Number_of_Contacts__c from Account where id = :b.id LIMIT 1];
       System.debug(ACC);
       System.assertEquals ( Integer.valueOf(ACC.Number_of_Contacts__c) ,0);
    }
    
    
    
}

I check if related contacts number is empty! :) 
raxa baberaxa babe
I’ve been surfing online more than three hours as of late, but I by no means found any fascinating article like yours. It is pretty worth enough for me. Personally, if all web owners and bloggers made excellent content as you did, the internet will probably be much more useful than ever before. Visit the gtacheatcode (https://gtacheatcode.com/) website for updated game cheats and click here for How GTA 5 cheats works? (https://gtacheatcode.com/gta-5-cheats-ps4/)
Prakhar Gupta 24Prakhar Gupta 24
// Class AccountProcess
public class AccountProcessor {
    @future
    public static void countContacts(List<Id> idList){
        List<Account> accMap=new List<Account> ();
        for(AggregateResult agg: [SELECT Account.Id,COUNT(Id)cn FROM Contact WHERE Account.Id IN :idList GROUP BY Account.Id]){
            Account ac=new Account(Id=(Id)agg.get('Id'));
            ac.Number_of_Contacts__c=(Integer)agg.get('cn');
            accMap.add(ac);
        }
       
       update accMap;
        
    }
}
// Class AccountProcessTEST
@istest
public class AccountProcessorTest {
    @istest static void acContact(){
        
        Account ac = new Account(Name='Prakhar');
        insert ac;
        Contact con1 = new Contact(LastName='Test 1',AccountId=ac.Id);
        insert con1;
        Contact con2 = new Contact(LastName='Test 2',AccountId=ac.Id);
        insert con2;
        List<Id> ids =new List<Id>();
        ids.add(ac.Id);
        List<AggregateResult> agg=new List<AggregateResult>();
        Test.startTest();
        AccountProcessor.countContacts(ids);
        agg =[SELECT Count(Id)cn FROM Contact WHERE Account.Id=:ac.Id];
        Test.stopTest();
        System.assertEquals(2,agg[0].get('cn'));       
    }
}
harish chitlaharish chitla
Hi, i am unable to create Number_of_Contacts__c , while creating  Number_of_Contacts__c it is giving an error like " field cannot take two consecutive underscores 

Please any help me out
Thank you.
 
AAYUSHI SHRIVASTAVAAAYUSHI SHRIVASTAVA
Hi Harish,
when you're creating a field on the accounts object, you just have to name the field label as "Number of Contacts". Number_of_Contacts__c will automatically be created when you save it.
(object manager>account>fields&relationship>new>choose number as the picklist>enter field label as: Number of Contacts> leave others as it is> next>next>save.)
Thanks.
Sushant clinicSushant clinic
This site (https://clinicinus.com/) is very good for bloggers, Developers,s, and coders. Just share very informational information. 
AviK18AviK18
Hi All,

 this is the code that worked for me 

CLASS:-

public class AccountProcessor {
    // future method
    @future
     public static void countContacts(List<Id> accountList){
        // Account List which we will use to bulk update 
        List<Account> accList=new List<Account> ();
         // read only sObject to store the result of query  
        for(AggregateResult conResult: [SELECT Account.Id,COUNT(Id)cn FROM Contact WHERE Account.Id IN :accountList GROUP BY Account.Id]){
            Account ac=new Account(Id=(Id)conResult.get('Id'));
            ac.Number_of_Contacts__c=(Integer)conResult.get('cn');
            accList.add(ac);
        }
       // bulk update the account
       update accList;
        
    }

}

TEST CLASS:-

  @IsTest
public class AccountProcessorTest {
     
    public static testmethod void TestAccountProcessorTest(){
      
        // creating account
        Account acc = new Account(Name='Avi');
        insert acc;
        // creating contact for the account
        Contact cont1 = new Contact(LastName='Avi1',AccountId=acc.Id);
        insert cont1;
        // creating 2nd contact for account
        Contact cont2 = new Contact(LastName='Avi2',AccountId=acc.Id);
        insert cont2;
        // List to store all Ids
        List<Id> totalIds =new List<Id>();
        totalIds.add(acc.Id);
        
        // Aggregate Result is a read-only sObject that can store the result of the query
        List<AggregateResult> conResult=new List<AggregateResult>();
        
        Test.startTest();
        AccountProcessor.countContacts(totalIds);
        conResult =[SELECT Count(Id)cn FROM Contact WHERE Account.Id=:acc.Id];
        Test.stopTest();
        
        System.assertEquals(2,conResult[0].get('cn'));         
       
  }
 
}
Atqua SidiqueAtqua Sidique
Hi All,

I am getting an error as "The Apex class does not appear using the '@future' annotation." Can someone help me, as I don't know where I am going wrong?

Thanks!
asaw asgeasaw asge
Hey, Please help to integrate the script with my blog. I'm using the netlify CMS platform for my ps4 router reviews (https://www.boneheadphone.com/best-gaming-router-for-ps4/) page.
Bruno Pereira 12Bruno Pereira 12

For this challenge, I developed the following code:

public class AccountProcessor {
    @future
    public static void countContacts(Id ids){
        Account a = [SELECT Id, Name FROM Account WHERE Id =: ids];
        List<Contact> listContact = [SELECT Id FROM Contact WHERE AccountId =:ids];
        a.Number_Of_Contacts__c = listContact.size();
        upsert a;
    }
}


And the following code for the TestClass:

@isTest
	public class AccountProcessorTest {
        @isTest static void TestSucess(){
            Account a = new Account();
            a.Name = 'Teste';
            insert a;
            
            Contact c = new Contact();
            c.LastName = 'Sobrenome Comum Teste';
            c.AccountId = a.Id;
            
            Contact c1 = new Contact();
            c1.LastName = 'Sobrenome Comum Teste';
            c1.AccountId = a.Id; 
            
            insert c;
            insert c1;
            
            Test.startTest();
            AccountProcessor.countContacts(a.Id);
            Test.stopTest();
        }
        
        
}

Simple, but Functional
deepashri hkdeepashri hk
Below worked for me efficiently:
1. Create the factory class method to create the number of accounts required to be created.
className: OlderAccountsUtility
public static List<Account> createAccounts(Integer  numOfAccounts) {
        List<Account> accountList = new List<Account>();
        for(Integer i=0;i<numOfAccounts;i++)
        {
            Account account = new Account(Name='TestAccount'+i);
            accountList.add(account);
        }
        insert accountList;
        return accountList;    
    }
2. Create the factory class method to create the related contacts for the account created above.
className: RandomContactFactory
public static List<Contact> createRelatedContact(Integer numContacts, String AccountId) {
        List<Contact> contacts = new List<Contact>();
        for(Integer i=0;i<numContacts;i++) {
            Contact contact = new Contact(FirstName='TestContact' + i, LastName='TestLastName',AccountId=AccountId);
            contacts.add(contact);
            System.debug('contact '+contact);
        }
        insert contacts;
        return contacts;
}

3. Use these factory methods to create the test data for testing and pass the same to have 100% code coverage.

@isTest
public class AccountProcessorTest {
    
    @isTest
    public static void countContactsTest()
    {
        List<Id> accountIds = new List<Id>();
        Account[] account = OlderAccountsUtility.createAccounts(1);
        for(Account a : account)
        {
            accountIds.add(a.Id);
            Contact[] relatedContact = RandomContactFactory.createRelatedContact(1,a.Id);
        }
        Test.startTest();
        AccountProcessor.countContacts(accountIds);
        Test.stopTest();
       
    }
}
typing monstertyping monster
English to hindi typing (https://typingmonster.com/english-to-hindi-typing) English to tamil typing (https://typingmonster.com/english-to-tamil-typing) are user to convert languages in hindi and tamil
 
doctor codiedoctor codie
Can we use this code to develope a mini accounting template for personal use or for a website (https://www.monitortvreviews.com/) ?
Soumya Mishra 14Soumya Mishra 14
public with sharing class InlineEditController
{
@Auraenabled
public static list<Inventory_Line_Items__c> getRelatedList(Id recordId)
{
        
List<Inventory_Line_Items_c> Conlist =[ SELECT EPIC_Namec, Use_Case_Namec, Line_Item_Descriptionc, Salesforce_Vlocity_Component_Namec,Complexityc,New_Modifiedc,Unitsc,Adjusterc,Total_Daysc,Total_Hrsc FROM Inventory_Line_Itemsc where Estimator_Detail_c =: recordId];
return Conlist;
}
    
@AuraEnabled
public static void updateRelatedList(List<Inventory_Line_Items__c> Conlist)
     {
          if(Conlist!= null && Conlist.size()>0)
          {
               update Conlist;
          }
         } 
}
how can i create a class that should have coverage 80%
David Campos 5David Campos 5
This site (https://surveytuts.com/) is very good for peoples who are looking to participate in surveys and win rewards.
Rick RoyRick Roy
Really impressive to visit this site and its great for developes and coding dudes.
https://hourstodaylist.com/
Rick RoyRick Roy
Iam basically beginner in code and still enjoy to write and help my collegaues in coding scripts
https://toysfeel.com/
Manoranjan S RManoranjan S R
public class AccountProcessor {
     @future
    public static void countContacts(List<Id> AccountIDs) {
        List<Account> acc = [select Id,Name from Account where Id IN :AccountIDs];
        for(Account a:acc){
               a.Number_of_Contacts__c = [select Count() from Contact where AccountId =:a.Id];  
        }
    }
}



@isTest
public class AccountProcessorTest {
    @isTest 
    public static void countContactsTest(){
        Account a = new Account(Name='TestAccount');
        insert a;
        
        List<Contact> cnts = new List<Contact>();
        List<Id> AId = new List<Id>();
        for (Integer i=0;i<3;i++) {
            cnts.add(new Contact(LastName='TestContact'+i, AccountId=a.Id));
            AId.add(a.Id);
        }
        insert cnts;
        Test.startTest();
        AccountProcessor.countContacts(AId);
        Test.stopTest();
            
    }           
}
Robert WhiskerRobert Whisker
Generally from Switzerland, implying that you'll have to datejust (https://identicalwatchess.to/) discharge a Swiss ledger to get one of the watches