<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>TestClass &#8211; Jitendra Zaa</title>
	<atom:link href="https://www.jitendrazaa.com/blog/tag/testclass/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.jitendrazaa.com/blog</link>
	<description>AI, Salesforce, ServiceNow &#38; Enterprise Tech Guides</description>
	<lastBuildDate>Wed, 10 May 2017 14:49:13 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>
<site xmlns="com-wordpress:feed-additions:1">87744916</site><atom:link rel="search" type="application/opensearchdescription+xml" title="Search Jitendra Zaa" href="https://www.jitendrazaa.com/blog/wp-json/opensearch/1.1/document" />	<item>
		<title>Test Setup method in Apex</title>
		<link>https://www.jitendrazaa.com/blog/salesforce/test-setup-method-in-apex-test-class/</link>
					<comments>https://www.jitendrazaa.com/blog/salesforce/test-setup-method-in-apex-test-class/#comments</comments>
		
		<dc:creator><![CDATA[Jitendra]]></dc:creator>
		<pubDate>Mon, 22 Feb 2016 02:51:04 +0000</pubDate>
				<category><![CDATA[Salesforce]]></category>
		<category><![CDATA[TestClass]]></category>
		<guid isPermaLink="false">http://www.jitendrazaa.com/blog/?p=5351</guid>

					<description><![CDATA[How to use setup method in Apex test classes]]></description>
										<content:encoded><![CDATA[<p style="text-align: justify;">In <a href="https://www.jitendrazaa.com/blog/salesforce/apex/faq-writing-test-class-in-salesforce/">previous blog post</a>, we discussed best practices of writing Test classes in Apex. In old school way, if we wanted to create records for test methods, helper or utility classes were favorite option for developers.</p>
<p style="text-align: justify;">However this approach has few disadvantages</p>
<ul>
<li style="text-align: justify;">Multiple Test classes could depend on these utility methods</li>
<li style="text-align: justify;">It creates tight coupling between classes</li>
<li style="text-align: justify;">Deployment could be slow if unnecessary test record being created for test methods</li>
<li style="text-align: justify;">If class to create test record is not marked with <strong>@isTest</strong> then it will count against allowed apex code in instance</li>
<li style="text-align: justify;">Test classes needs to explicitly call method to create test records</li>
</ul>
<p><span id="more-5351"></span></p>
<h3>Test Setup (@testSetup) Methods in Test Class</h3>
<p>Apex has introduced new method in Test class known as &#8220;Test Setup&#8221;. Following are some highlights and considerations of using Test Setup method in Test classes :</p>
<ul>
<li>It needs to be marked with <strong>@testSetup</strong> annotation in Test class</li>
<li>One Test class can have only one <strong>@testSetup</strong> methods</li>
<li>These test setup methods are implicitly invoked before each test methods</li>
<li>These methods can be used to create test records specific to Test class</li>
<li>It helps to keep Test classes isolated and independent of helper or utility classes</li>
<li>It can&#8217;t be used if Test class is marked with <strong>@isTest(SeeAllData=true)</strong></li>
<li>If error occurs in setup method then entire test class fails</li>
<li>If non-test method is called from setup method then no code coverage is calculated for non-test method</li>
<li>If multiple set up method is written in Test class then sequence of execution of those methods are not guaranteed</li>
</ul>
<p>Below class shows sample code of Test method in action. It creates 200 lead records in test setup method (<strong>@testSetup</strong>) and checks whether 200 records are created or not in test method.</p>
<pre class="brush: java; title: ; notranslate">
@iSTest
public class LeadProcessorTest {   

    //below test setup method will be invoked
    // implicitly before every test methods 
    @testsetup
    static void createLead(){
        List&lt;Lead&gt; lstLead = new List&lt;Lead&gt;();        
        for(Integer i = 0 ; i&lt;200 ; i++) {
            lstLead.add(new Lead(lastName = 'testLName'+i , Company = 'Salesforce'));
        } 
        insert lstLead ;
    }
    
   //Check whether records created in test method
   //is accessible or not
    public static testMethod void test(){
        System.assertEquals(200, &#x5B;SELECT COUNT() FROM Lead Where company = 'Salesforce']);
    }
}
</pre>
<p>Resource : <a href="https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_testing_testsetup_using.htm">official Salesforce documentation</a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.jitendrazaa.com/blog/salesforce/test-setup-method-in-apex-test-class/feed/</wfw:commentRss>
			<slash:comments>5</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">5351</post-id>	</item>
		<item>
		<title>Using Test.loadData to import records with relationship</title>
		<link>https://www.jitendrazaa.com/blog/salesforce/using-test-loaddata-to-import-records-with-relationship/</link>
					<comments>https://www.jitendrazaa.com/blog/salesforce/using-test-loaddata-to-import-records-with-relationship/#comments</comments>
		
		<dc:creator><![CDATA[Jitendra]]></dc:creator>
		<pubDate>Wed, 06 Jan 2016 05:58:44 +0000</pubDate>
				<category><![CDATA[Salesforce]]></category>
		<category><![CDATA[static resource]]></category>
		<category><![CDATA[TestClass]]></category>
		<guid isPermaLink="false">http://www.jitendrazaa.com/blog/?p=5152</guid>

					<description><![CDATA[There are many resources and documents available around how to use Test.loadData to create test records in Apex class. As per best practice of writing Test classes in Apex, Its good idea to store master data (aka Seed, Reference data) in static resource and load it in Test classes using &#8220;Test.loadData&#8221; method. It will save lots [&#8230;]]]></description>
										<content:encoded><![CDATA[<p style="text-align: justify;">There are many resources and documents available around how to use Test.loadData to create test records in Apex class. As per <a href="https://www.jitendrazaa.com/blog/salesforce/apex/faq-writing-test-class-in-salesforce/">best practice of writing Test classes</a> in Apex, Its good idea to store master data (aka Seed, Reference data) in static resource and load it in Test classes using &#8220;Test.loadData&#8221; method. It will save lots of code around creating test records and at the same time easy to maintain. We can store records of Custom settings, standard or custom object which can be used frequently in our code. One of the best functionality to make writing Test classes more easier, As we don&#8217;t need to concentrate on writing code for creating data, time can be used to assert actual functionality.</p>
<figure id="attachment_5160" aria-describedby="caption-attachment-5160" style="width: 864px" class="wp-caption alignleft"><a href="https://i0.wp.com/www.jitendrazaa.com/blog/wp-content/uploads/2016/01/Test.loadData-and-Static-resource-in-Salesforce.png?ssl=1" rel="attachment wp-att-5160"><img data-recalc-dims="1" fetchpriority="high" decoding="async" class="size-full wp-image-5160" src="https://i0.wp.com/www.jitendrazaa.com/blog/wp-content/uploads/2016/01/Test.loadData-and-Static-resource-in-Salesforce.png?resize=864%2C525&#038;ssl=1" alt="Test.loadData and Static resource in Salesforce" width="864" height="525" srcset="https://i0.wp.com/www.jitendrazaa.com/blog/wp-content/uploads/2016/01/Test.loadData-and-Static-resource-in-Salesforce.png?w=864&amp;ssl=1 864w, https://i0.wp.com/www.jitendrazaa.com/blog/wp-content/uploads/2016/01/Test.loadData-and-Static-resource-in-Salesforce.png?resize=300%2C182&amp;ssl=1 300w, https://i0.wp.com/www.jitendrazaa.com/blog/wp-content/uploads/2016/01/Test.loadData-and-Static-resource-in-Salesforce.png?resize=768%2C467&amp;ssl=1 768w, https://i0.wp.com/www.jitendrazaa.com/blog/wp-content/uploads/2016/01/Test.loadData-and-Static-resource-in-Salesforce.png?resize=624%2C379&amp;ssl=1 624w" sizes="(max-width: 864px) 100vw, 864px" /></a><figcaption id="caption-attachment-5160" class="wp-caption-text">Test.loadData and Static resource in Salesforce</figcaption></figure>
<p style="text-align: justify;">So the question is, How can we load related records using Test.loaddata() method ? Simply by creating fake Salesforce Ids, that&#8217;s right !!! It is possible.</p>
<p style="text-align: justify;">In this post, we will be loading two CSV files in static resource. One static resource file is used to create Account records and Other CSV will be used to create child contacts of Account.<span id="more-5152"></span></p>
<figure id="attachment_5155" aria-describedby="caption-attachment-5155" style="width: 188px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.jitendrazaa.com/blog/wp-content/uploads/2016/01/Account-CSV-file-for-Static-resource.png?ssl=1" rel="attachment wp-att-5155"><img data-recalc-dims="1" decoding="async" class="size-full wp-image-5155" src="https://i0.wp.com/www.jitendrazaa.com/blog/wp-content/uploads/2016/01/Account-CSV-file-for-Static-resource.png?resize=188%2C205&#038;ssl=1" alt="Account CSV file for Static resource to use in Test.loadData method" width="188" height="205" /></a><figcaption id="caption-attachment-5155" class="wp-caption-text">Account CSV file for Static resource to use in Test.loadData method</figcaption></figure>
<figure id="attachment_5156" aria-describedby="caption-attachment-5156" style="width: 320px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.jitendrazaa.com/blog/wp-content/uploads/2016/01/Contact-CSV-file-for-Static-resource.png?ssl=1" rel="attachment wp-att-5156"><img data-recalc-dims="1" decoding="async" class="size-full wp-image-5156" src="https://i0.wp.com/www.jitendrazaa.com/blog/wp-content/uploads/2016/01/Contact-CSV-file-for-Static-resource.png?resize=320%2C238&#038;ssl=1" alt="Contact CSV file for Static resource to use in Test.loadData method" width="320" height="238" srcset="https://i0.wp.com/www.jitendrazaa.com/blog/wp-content/uploads/2016/01/Contact-CSV-file-for-Static-resource.png?w=320&amp;ssl=1 320w, https://i0.wp.com/www.jitendrazaa.com/blog/wp-content/uploads/2016/01/Contact-CSV-file-for-Static-resource.png?resize=300%2C223&amp;ssl=1 300w" sizes="(max-width: 320px) 100vw, 320px" /></a><figcaption id="caption-attachment-5156" class="wp-caption-text">Contact CSV file for Static resource to use in Test.loadData method</figcaption></figure>
<p>As we can see in above image, dummy Salesforce Id is provided in Account CSV and same ID is used in Contact CSV file in column &#8220;AccountId&#8221;.</p>
<p>Below code snippet proves that it is working.</p>
<pre class="brush: java; title: ; notranslate">
/**
 * Author	:	Jitendra Zaa
 * Desc		:	Sample Test class to demonstrate usage of Test.loadData to import related records 
 * */

@isTest
public class StaticResourceTest {

      static testmethod void staticResourceLoad(){
        
        //Load CSV file saved in static resource  
        List&lt;SObject&gt; lstAcc = Test.loadData(Account.sObjectType,'AccountLoad_Test');
        List&lt;SObject&gt; lstCon = Test.loadData(Contact.sObjectType,'ContactLoad_Test');
        
        //Confirm that total number of accounts created are 5
        System.assertEquals(lstAcc.size(), 5);
        
        for(Account a : &#x5B;SELECT Id, Name, (SELECT FirstName,LastName FROM Contacts) FROM Account where Id IN :lstAcc]){
            //confirm that every Account has associated child contact
            System.assertNotEquals(null, a.contacts);
            
            //confirm that every Account has exactly 2 contacts
            System.assertEquals(a.contacts.size(), 2);
        }
    }
}
</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://www.jitendrazaa.com/blog/salesforce/using-test-loaddata-to-import-records-with-relationship/feed/</wfw:commentRss>
			<slash:comments>14</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">5152</post-id>	</item>
		<item>
		<title>FAQ and Best Practices of Test Classes in Apex</title>
		<link>https://www.jitendrazaa.com/blog/salesforce/apex/faq-writing-test-class-in-salesforce/</link>
					<comments>https://www.jitendrazaa.com/blog/salesforce/apex/faq-writing-test-class-in-salesforce/#comments</comments>
		
		<dc:creator><![CDATA[Jitendra]]></dc:creator>
		<pubDate>Sat, 15 Feb 2014 08:59:43 +0000</pubDate>
				<category><![CDATA[Apex]]></category>
		<category><![CDATA[FAQ]]></category>
		<category><![CDATA[Interview Questions]]></category>
		<category><![CDATA[TestClass]]></category>
		<category><![CDATA[Visualforce]]></category>
		<guid isPermaLink="false">http://JitendraZaa.com/blog/?p=3694</guid>

					<description><![CDATA[Here I am going to share few answers related to Test Classes, which is being asked many times to me by novice Programmers. Please feel free to post Comments if your question is not answered here. I will try my best to add those Questions in this article. If you want to learn Test Class [&#8230;]]]></description>
										<content:encoded><![CDATA[<p style="text-align: justify;">Here I am going to share few answers related to Test Classes, which is being asked many times to me by novice Programmers. Please feel free to post Comments if your question is not answered here. I will try my best to add those Questions in this article. If you want to learn Test Class from very basic,<a title="How to write Test Class in Salesforce" href="https://jitendrazaa.com/blog/salesforce/step-by-step-salesforce-tutorial-%E2%80%93-creating-trigger-and-test-cases-%E2%80%93-6-of-6/"> you can check this article also</a>.</p>
<ol>
<li><a title="Best Practices for Test Classes" href="#Q1">Best Practices for Test Classes</a></li>
<li><a href="#Q10">Use of SmartFactory to auto generate test data</a></li>
<li><a title="Test method of Controller Extension for StandardController" href="#Q2">Test method of Controller Extension for StandardController</a></li>
<li><a title="Test method of Controller Extension for StandardSetController" href="#Q3">Test method of Controller Extension for StandardSetController</a></li>
<li><a title="Why getSelected() method of StandrdSetController is not working" href="#Q4">Why getSelected() method of StandrdSetController is not working</a></li>
<li><a title="sample Template of class which generates Dummy Data" href="#Q5">sample Template of class which generates Dummy Data</a></li>
<li><a title="checking Error Page Messages in Test Classes" href="#Q6">checking Error Page Messages in Test Classes</a></li>
<li><a title="How to set Current Visualforce Parameter in Apex Test class" href="#Q7">Setting Visualforce Page Parameter</a></li>
</ol>
<div id="Q1">
<p><strong>What are some Best Practices while writing Test Classes ?</strong></p>
<p>Well, It differs from person to person, as every programmer has its own style of writing code. However I will list few of mine.</p>
<ul>
<li style="text-align: justify;">Very important and first, &#8220;Test Coverage Target Should not be limited to 75%&#8221;. It is not about coverage, It is about testing complete functionality. It will be always better if your code fails during test execution, It will be less devastating than failing functionality after product release.</li>
<li style="text-align: justify;">If possible Don&#8217;t use <strong>seeAllData=true</strong>, Create your Own Test Data.</li>
<li style="text-align: justify;">Always use <strong>@testSetup</strong> method dedicated to create test records for that class. This is newly added annotation and very powerful. Any record created in this method will be available to all test methods of that class. Using @testSetup method will improve test execution performance by creating test records only once for that class. If you are not using this, means test record is created in each TestMethod which will be very slow. <a href="https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_testing_testsetup_using.htm">Read this Salesforce documentation for more information</a>.</li>
<li style="text-align: justify;">Create Different Class which will create Dummy Data for testing, and use it everywhere (You have to be very careful, as sometimes it may slow down test class execution by creating unnecessary data which does not require by every test methods. So few developer prefer test data creation per Test class)</li>
<li style="text-align: justify;">If your Object&#8217;s Schema is not changing frequently, you can create CSV file of records and load in static resource. This file will act as Test data for your Test Classes.</li>
<li style="text-align: justify;">Use As much as Assertions like System.AssertEquals or System.AssertNotEquals</li>
<li style="text-align: justify;">Use <strong>Test.startTest()</strong> to reset Governor limits in Test methods</li>
<li style="text-align: justify;">If you are doing any Asynchronous operation in code, then don&#8217;t forget to call <strong>Test.stopTest()</strong> to make sure that operation is completed.</li>
<li style="text-align: justify;">Use <strong>System.runAs()</strong> method to enforce OWD and Profile related testings. This is very important from Security point of View.</li>
<li style="text-align: justify;">Always try to pass null values in every methods. This is the area where most of program fails, unknowingly.</li>
<li style="text-align: justify;">Always test Batch Capabilities of your code by passing 20 to 100 records.</li>
<li style="text-align: justify;">Use <strong>Test.isRunningTest()</strong> in your code to identify that context of class is Test or not. You can use this condition with OR (||) to allow test classes to enter inside code bock. It is very handy while testing for webservices, we can generate fake response easily.</li>
<li style="text-align: justify;"><strong>@TestVisible</strong> annotation can be used to access private members and methods inside Test Class. Now we don&#8217;t need to compromise with access specifiers for sake of code coverage.</li>
<li style="text-align: justify;">End your test class with &#8220;_Test&#8221;. So that in Apex Class list view, Main class and Test class will come together, resulting easy navigation and time saver.</li>
</ul>
</div>
<p><span id="more-3694"></span></p>
<hr />
<div id="Q10">
<p><strong>Use of SmartFactory to auto generate test data</strong></p>
<p style="text-align: justify;">This is very common pattern where we create test data in some utility method ans reuse it across test methods. However change in requirement is inevitable and many validation rules and mandatory fields gets introduced in application and test methods starts breaking. We can resolve this issue by using <a href="https://github.com/mbotos/SmartFactory-for-Force.com">unmanaged package available on github</a> which creates Test data and hierarchy automatically using dynamic Apex and make sure all required fields are populated.</p>
<p>Just use SmartFactory in your tests to create objects:</p>
<pre class="brush: java; title: ; notranslate">
Account account = (Account)SmartFactory.createSObject('Account');
</pre>
<p>To cascade and create objects for lookup and master-detail relationships:</p>
<pre class="brush: java; title: ; notranslate">
Contact contact = (Contact)SmartFactory.createSObject('Contact', true);
</pre>
<p>The same syntax is used for custom objects:</p>
<pre class="brush: java; title: ; notranslate">
Custom_Object__c customObject = (Custom_Object__c)SmartFactory.createSObject('Custom_Object__c');
</pre>
</div>
<div id="Q2">
<p><strong>How to write Test method of Controller Extension for StandardController ?</strong></p>
<p>Example :</p>
<pre class="brush: java; title: ; notranslate">
//Lets Assume we are writing Controller Extension for Account
Account acct = &#x5B;SELECT ID FROM Account LIMIT 1];

//Start Test Context, It will reset all Governor limits
Test.startTest();

//Inform Test Class to set current page as your Page where Extension is used
Test.setCurrentPage(Page.YOUR_PAGE);

//Instantiate object of &quot;ApexPages.StandardController&quot; by passing object
ApexPages.StandardController stdController = new ApexPages.StandardController(acct);

//Now, create Object of your Controller extension by passing object of standardController
YOUR_Extension ext = new YOUR_Extension(stdController);

//Here you can test all public methods defined on Extension &quot;ext&quot;
//..... your code

//Finish Test
Test.stopTest();
</pre>
</div>
<hr />
<div id="Q3"><strong>How to write Test method of Controller Extension for StandardSetController ?</strong></div>
<div></div>
<div>
<p>In Same way, with few modification :</p>
<pre class="brush: java; title: ; notranslate">
//Lets Assume we are writing Controller extension to use on List View of Account
List &lt;Account&gt; acctList = &#x5B;SELECT ID FROM Account];

//Start Test Context, It will reset all Governor limits
Test.startTest();

//Inform Test Class to set current page as your Page where Extension is used
Test.setCurrentPage(Page.YOUR_PAGE);

//Instantiate object of &quot;ApexPages.StandardSetController&quot;by passing array of records
ApexPages.StandardSetController stdSetController = new ApexPages.StandardSetController(acctList);

//Now, create Object of your Controller extension by passing object of standardSetController
YOUR_Extension ext = new YOUR_Extension(stdSetController);

//Here you can test all public methods defined on Extension &quot;ext&quot;
//..... your code

//Finish Test
Test.stopTest();
</pre>
</div>
<hr />
<div id="Q4">
<p><strong>Why getSelected() method of StandrdSetController is not returning anything?</strong></p>
<p>You might be in situation that getSelected() method is not returning anything in your test method  inspite of proper coding. In Actual scenario we select records in ListView and after clicking on custom button, StandardSetController&#8217;s getSelected() method returns selected record in Controller Extension. So, to Select records programmatically  in Test method we have to use method &#8220;setSelected()&#8221; as shown in below code.</p>
<pre class="brush: java; highlight: [14]; title: ; notranslate">
//Lets Assume we are writing Controller extension to use on List View of Account
List &lt;acctList&gt; = &#x5B;SELECT ID FROM Account];

//Start Test Context, It will reset all Governor limits
Test.startTest();

//Inform Test Class to set current page as your Page where Extension is used
Test.setCurrentPage(Page.YOUR_PAGE);

//Instantiate object of &quot;ApexPages.StandardSetController&quot; by passing array of records
ApexPages.StandardSetController stdSetController = new ApexPages. StandardSetController(acctList);

//Here, you are selecting records programmatically, which will be available to method &quot;getSelected()&quot;
stdSetController.setSelected(acctList);

//Now, create Object of your Controller extension by passing object of standardSetController
YOUR_Extension ext = new YOUR_Extension(stdSetController);

//Here you can test all public methods defined on Extension &quot;ext&quot;
//..... your code

//Finish Test
Test.stopTest();
</pre>
</div>
<hr />
<div id="Q5"><strong>Any sample Template for method or class which generates Dummy Data?</strong></div>
<div></div>
<div>
<p>You can create methods something like below to generate TestRecords. It will change on requirement however will give some idea.</p>
<pre class="brush: java; title: ; notranslate">
/**
*	Utility class used for generating Dummy Data for Test Methods
**/
public class DummyData
{
	/**
	*	Description : This method will generate List of Account with Dummy Data
	*
	*	Parameters :
	*	@totalRecords : How many Records you want to generate ?
	*	@withIds : Do you want returned records with generateId? If null then false
	**/
	public static List&lt;Account&gt; getAccounts(Integer totalRecords, Boolean withIds)
	{
		List&lt;Account&gt; retList = new List&lt;Account&gt;();
		if(withIds == null)
			withIds = false;

		for(Integer i=0;i&lt;totalRecords;i++)
		{
			Account a = new Account(Name = constructTestString(20));
			retList.add(a);
		}
		if(withIds)
			insert retList;

		return retList;
	}

	/**
	*	This method is used to generate Random String of supplied length
	*/
	public static String constructTestString(Integer length) {
		Blob blobKey = crypto.generateAesKey(128);
		String key = EncodingUtil.convertToHex(blobKey);
		return key.substring(0,length);
	}
}
</pre>
</div>
<hr />
<div id="Q6">
<p style="text-align: justify;"><strong>How to check Error Page Messages in Test Classes to ensure that messages are displayed as expected on Visualforce Page ?</strong></p>
<p>Assume that you have one Controller class which adds error message to Visualforce page.</p>
<pre class="brush: java; title: ; notranslate">
public class DemoController
{
    //... some code

    public PageReference somemethod()
    {
        //Check for some validation. like User is Authorized or not ?
        if(!validate())
        {
             //Means User is not Authorized for this operation, Add error on Visualforce page
             Apexpages.addMessage( new ApexPages.Message (ApexPages.Severity.ERROR, 'User is not Authorized to perform this Operation'));
             return null;
        }
        return Page.SomePage;
    }
}
</pre>
<p>Now, lets say you want to check whether error message is added on visualforce page or not in Test Class.</p>
<pre class="brush: java; title: ; notranslate">
@isTest
public class DemoController_Test
{
    public static testMethod void someMethod_Test()
    {
        Test.StartTest();

        //Set Context for Current page in Test Method
        Test.setCurrentPage(Page.yourpage);

        //... some code Here, which will produce error in Apex:PageMessages tag
        List&lt;Apexpages.Message&gt; msgs = ApexPages.getMessages();

        boolean isErrorMessage = false;

        for(Apexpages.Message msg : msgs){
            if (msg.getDetail().contains('User is not Authorized to perform this Operation') )
                isErrorMessage  = true;
        }
        //Assert that the Page Message was Properly Displayed
        system.assert(isErrorMessage );

    }
}
</pre>
<p>If you are looking on how to add &#8220;Page error message&#8221; in Visualforce through Apex, You can see <a title="Latest Salesforce Interview Questions – Part 4 – Related to Dynamic Apex" href="https://jitendrazaa.com/blog/salesforce/very-useful-tips-and-tricks-of-the-apex-salesforce-interview-questions-part-4/">this article</a>.</p>
<hr />
</div>
<div id="Q7"><strong>How to set Page Parameters for Visualforce page in Test Classes ?</strong></div>
<div></div>
<div>
<p>First, we need to set Current page in Test method and use &#8220;ApexPages&#8221; class. Example of code snippet shown below :</p>
<pre class="brush: java; title: ; notranslate">
@isTest
public class Your_TestClass
{
    public static testMethod void yourmethodName()
    {
        //... your initialization code here

        //Set current Page Context here, consider page name &quot;Demo&quot;
        Test.setCurrentPage(Test.Demo);

        //Now set Parameters for page &quot;Demo&quot;
        ApexPages.currentPage( ).getParameters( ).put( 'parameterName' , 'param Value');

        //... Your remaining logic here
    }
}
</pre>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://www.jitendrazaa.com/blog/salesforce/apex/faq-writing-test-class-in-salesforce/feed/</wfw:commentRss>
			<slash:comments>12</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3694</post-id>	</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/?utm_source=w3tc&utm_medium=footer_comment&utm_campaign=free_plugin

Page Caching using Disk: Enhanced 
Minified using Disk

Served from: www.jitendrazaa.com @ 2026-04-17 08:51:29 by W3 Total Cache
-->