Notifications
Clear all
Oct 04, 2021 9:29 am
Code snipped to get a list of Ids from Maps.
1 Reply
Oct 04, 2021 9:42 am
// Say if you want to test and run a method in the anonymous window by passing it a list of Ids
Map<Id, Account> accounts = new Map<Id, Account>([SELECT Id FROM Account]);
List<Id> accountIds = new List<Id>(accounts.keySet()); // convert the Ids in the Map to a list
AccountProecssor.countContacts(accountIds);
// Actual method:
public without sharing class AccountProcessor { @future public static void countContacts(List<Id> AccountIds){ List<Account> accounts = [SELECT Id, (SELECT Id FROM Contacts) FROM Account WHERE Id IN :AccountIds]; for (Account acc : accounts){ acc.Number_Of_Contacts__c = acc.Contacts.size(); } update accounts; } }
// Its test class:
@isTest private class AccountProcessorTest { @isTest private static void countContactsTest() { // Load test data List<Account> accounts = new List<Account>(); for (Integer i=0; i<300; i++) { accounts.add(new Account(Name = 'Test Account' + i)); } insert accounts; List<Contact> contacts = new List<Contact>(); List<Id> accountIds = new List<Id>(); for (Account acc : accounts) { contacts.add(new Contact(FirstName = acc.Name, LastName = 'Test Contact', AccountId = acc.Id)); accountIds.add(acc.Id); } insert contacts; // Do the test Test.startTest(); AccountProcessor.CountContacts(accountIds); Test.stopTest(); // Check result List<Account> accs = [SELECT Id, Number_Of_Contacts__c FROM Account]; for (Account acc : accs) { System.assertEquals(1, acc.Number_Of_Contacts__c, 'Error: Expected at least one contact'); } } }
After running the method, you can go got Apex Jobs in Setup to view the future job that has run.
Note: In future methods (asynchronous) or for synchronous methods, max number of DMLs will be 2000 and max records that can be processed is 50,000. If your requirement is more, you will need to use batch apex.