Tuesday 7 October 2014

Set Parameter in Test Class


While writing test classes we often stuck with some parameters which need to be set to test the logic further, some developers try to avoid those parameters with Test.isRunning() in there logic which is not a good practice.

Salesforce powers us to set those parameter in Test Class. Suppose I am passing an Id of an Account in my url and on basis of Id I am querying Account.

public with sharing class ParameterController {
  
    private Id accId;
    public Account accDetail{get;set;}
    public ParameterController() {
        accId = ApexPages.CurrentPage().getParameters().get('Id');
    }
  
    public void accountDetails() {
        system.debug('  Account Id ' + accId);
        accDetail = [Select Id, Name, AnnualRevenue From Account Where Id =: accId];
        if(accDetail == null) {
            system.debug(' Some Logic');
        } else {
            system.debug(' Some Logic');
        }
    }

}


When I tried to write Test Class If I don't set the Id I will get an null point exception but to avoid the exception and to test my Class I can set the Id or any parameter as below

@isTest
public class ParameterController_Test {
    static Account testAccount() {
        Account newAccount = new Account();
        newAccount.Name = 'Test Account';
        newAccount.AnnualRevenue = 100;
        return newAccount;
    }
   
    static testMethod void accountDetails_Test(){

        Account newAccount = ParameterController_Test.testAccount();
        insert newAccount;
        PageReference ref = Page.Your_Page_Name;

        Test.setCurrentPage(ref);

        ApexPages.currentPage().getParameters().put('Id', newAccount.Id);

        ParameterController controller = new ParameterController();

        controller.accountDetails();
    }
}



Set the Parameters as

PageReference ref = Page.Your_Page_Name;

Test.setCurrentPage(ref);  

ApexPages.currentPage().getParameters().put('Id', newAccount.Id);  


Also refer ApexPages Method : click here

No comments:

Post a Comment