public class AccountHelper {
@future
public static void UpdateAccounts(List<Id> accountIds){
//Get those records based on the IDs
List<Account> accList = [SELECT Name FROM Account WHERE Id IN : accountIds];
//Process records
}
}
Test Class:
@isTest
public class TestAccountHelper {
private static User CreateUser(){
String orgId = UserInfo.getOrganizationId();
String standardUserProfileId = [SELECT Id From Profile WHERE Name = 'Standard User'].Id;
User u = new User(
FirstName = 'Test',
LastName = 'User',
Alias = 'TestUser',
profileId = standardUserProfileId ,
Email = orgId + '@test.org',
Username = orgId + '@test.org',
EmailEncodingKey = 'ISO-8859-1',
LanguageLocaleKey = 'en_US',
LocaleSidKey = 'en_US',
TimeZoneSidKey = 'America/Los_Angeles'
);
insert u;
return u;
}
private static Account CreateAccount(){
Account acc = new Account( Name = 'Test Account',
Type = 'Technology Partner',
Industry = 'Technology',
Phone = '9898989898'
);
insert acc;
return acc;
}
private static testMethod void testUpdateAccounts(){
User u = CreateUser();
System.runAs(u) {
Account acc = CreateAccount();
List<Id> accountIds = new List<Id>();
accountIds.add(acc.Id);
Test.startTest();
AccountHelper.UpdateAccounts(accountIds);
Test.stopTest();
}
//Verify account is inserted
List<Account> accList = [SELECT Id From Account WHERE Name = 'Test Account'];
System.assertEquals(1, accList.size());
}
}
public class AccountExtension {
public Account acc {get; set;}
//Constructor
public AccountExtension(ApexPages.StandardController stdCtrl) {
//Get Account Id
Id accountId = stdCtrl.getId();
//Get Account Required Information
acc = [SELECT Id, Name, Business_Unit__c, Shipping_Country_Name__c FROM Account WHERE Id = : accountId];
}
}
Here in below example the apex trigger is on “Account” object, to check duplicate Account Names.
Apex Trigger:
trigger AccountTrigger on Account (before Insert, before Update) {
Map<String, Account> accMap = new Map<String, Account>();
for (Account acc : System.Trigger.new) {
//Make sure you don't treat account Name that isn't changing during an update as a duplicate.
if (System.Trigger.isInsert || (acc.Name != System.Trigger.oldMap.get(acc.Id).Name)) {
//Make sure another new account isn't also a duplicate
if (accMap.containsKey(acc.Name)) {
acc.Name.addError('An account already exist with same name.');
} else {
accMap.put(acc.Name, acc);
}
}
}
//Query to find all the Accounts in the database that have the same name as any of the Accounts being inserted or updated.
for (Account acc : [SELECT Name FROM Account
WHERE Name IN :accMap.KeySet()]) {
Account newAcc = accMap.get(acc.Name);
newAcc.Name.addError('An account already exist with same name.');
}
}
Here is the Test Class for the above apex trigger. Test Class: