Tag Archives: Test Class

Test Class for Batch Apex in Salesforce

Batch Class:

global class BatchAccount implements Database.Batchable<sObject> 
{
    global Database.QueryLocator start(Database.BatchableContext BC) {
		
        return Database.getQueryLocator('SELECT Id,Name FROM Account');
    }
	
    global void execute(Database.BatchableContext BC, List<Account> scope) {
		
        for(Account a : scope)
        {
            a.Name = a.Name + ' Updated';
        }
        update scope;
    }
	
    global void finish(Database.BatchableContext BC) {
		
    }
}

Test Class:

@isTest 
public class BatchAccountTest 
{
    static testMethod void test() 
    {
        List<Account> accList = new List<Account>();
        for(Integer i = 0 ; i < 200; i++)
        {
            Account acc = new Account();
            acc.Name = 'Name' + i;
            accList.add(acc);
        }
        Insert accList;
        
		Test.startTest();
		BatchAccount obj = new BatchAccount();
		DataBase.executeBatch(obj); 
		Test.stopTest();
		
		//Verify accounts updated
		List<Account> accUpdatedList = [SELECT Id, Name FROM Account];
		System.assert(accUpdatedList[0].Name.Contains('Updated'));
    }
}

Test Class For Future Method

Future Method:

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

Add Record Type in Test Class

Sample Code:

@isTest()
public class TestUtils {
    
    private static testmethod  void CreateAccount(){
        //Get Account Record Type Id
        Id accountRecordTypeId = Schema.SObjectType.Account.getRecordTypeInfosByName().get('DeveloperNameOfRecordType').getRecordTypeId();
        
        //Create Account
        Account acc = new Account();
        acc.Name ='Test Account';
        acc.Industry = 'Retail';
        acc.AccountNumber = '123456';
        acc.RecordTypeId = accountRecordTypeId;
        Insert acc;
    }
}

Test Class for Controller Extension

Apex Extension:

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

Apex Test Class:

@isTest()
public class TestUtils {
    
    private static testmethod  void CreateAccount(){
        
        //Create Account
        Account acc = new Account();
        acc.Name ='Test Account';
        acc.Industry = 'Retail';
        acc.AccountNumber = '123456';
        Insert acc;
        system.assertEquals(true,acc.Id != null);

        //Add Pagereference
        PageReference pageRef = Page.AccountPage;
        Test.setCurrentPage(pageRef);
        
        //Pass Standard controller Parameter
        pageRef.getParameters().put('Id', String.valueOf(acc.Id));
        String accountId = ApexPages.currentPage().getParameters().get('id');
        system.assertEquals(true, accountId != null);
        ApexPages.StandardController sc = new ApexPages.StandardController(acc);
        AccountExtension accExtn = new AccountExtension(sc);
    }
}

Test Class For Apex Trigger

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:

@isTest
private class TestAccountTriggers {

    static testMethod void AccountTriggerUnitTest() {
	
        Account acc1 = new Account();
        acc1.Name = 'ABC Corp Ltd';
        acc1.Type = 'Prospect';
        acc1.Industry = 'Banking';
        Insert acc1;
		
        Account acc2 = new Account();
        acc2.Name = 'ABC Corp Ltd';
        acc2.Type = 'Prospect';
        acc2.Industry = 'Apparel';
		
        try
        {
        	Insert acc2;
        }
        catch(System.DMLException e)
        {
        	System.assert(e.getMessage().contains('An account already exist with same name.'));
        }
    }
}