function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Robert RobinsonRobert Robinson 

Writing a Controller extension test class

I am trying to create a test class for a controller extenstion that performs a SOQL query and sets up the VF page for pagination. Most test class examples that I have found have been for insertion of records, not data selection and listing. Can someone provide suggestions on the controller extension shown below? Thanks. 

public class DealList{    
 public Integer noOfRecords{get; set;}    
 public Integer size{get;set;}     
 public boolean showHeaderSideBar{get;set;}     
 public String redirectUrl {get;set;}     
ApexPages.StandardController controller;    
private boolean fullscreen;    
public DealList(ApexPages.StandardController controller) {        
this.controller = controller;       
 //check if page needs to be opened in full screen mode        
String value = ApexPages.currentPage().getParameters().get('fullscreen');        
if(String.isNotBlank(value) && value == 'true'){            
fullscreen = true;            
showHeaderSideBar = true;        }else{             
fullscreen = false;             
showHeaderSideBar = false;           
   }    
}     
public ApexPages.StandardSetController deals{          
get{             
if(deals == null){                 
if(fullscreen) size = 100;                 
if(size==null) size=5;                 
deals = new ApexPages.StandardSetController(Database.getQueryLocator( [Select Name, Location__c, Asset_Type__c, Underwriter__c, Amount__c, Stage__c, Estimated_Close__c, Closing_Probability_Category__c                    
    from Deal__c                     
     where Account_Name__c = :controller.getId()                    
       and Status__c = 'Open']));                 
      deals.setPageSize(size);                 
       noOfRecords = deals.getResultSize();             
}             
return deals;         
}         
set;     
}     
public Boolean hasNext {         
get {             
return deals.getHasNext();         
}         
set;     
}     
public Boolean hasPrevious {         
get {             
return deals.getHasPrevious();        
 }         
set;     
}     
public Integer pageNumber {         
get {             
return deals.getPageNumber();        
 }         
set;     
}     
public void first() {
        deals.first();     
}     
public void last() {         
deals.last();     
}     
public void previous() {         
deals.previous();    
 }     
public void next() {         
deals.next();    
 }     
public PageReference refreshPageSize() {          
deals.setPageSize(size);          
return null;     
}     
public void showAll(){         
redirectUrl = '/apex/AcctDealRelatedList?id='+controller.getId()+'&fullscreen=true';     
}     
public void saveDeals(){         
try {             
deals.save();         

catch (Exception e) {             
ApexPages.addMessages(e);         
}     
}
}
Best Answer chosen by Robert Robinson
Nayana KNayana K
@isTest
public class DealListTest
{
	static testMethod void testDealListPage() 
	{
	
		Account objAccount = new Account(Name = 'Test Acc');
		insert objAccount;
		
		/* Assuming Name is not an auto number here. Please populate all the required field value pairs.*/
		List<Deal__c> lstDeal = new List<Deal__c>{	new Deal__c(	Name = 'Test Deal1', Account_Name__c = objAccount.Id, 
																	Status__c = 'Open'),
													new Deal__c(	Name = 'Test Deal2', Account_Name__c = objAccount.Id, 
																	Status__c = 'Open'),
													new Deal__c(	Name = 'Test Deal3', Account_Name__c = objAccount.Id, 
																	Status__c = 'Open'),
													new Deal__c(	Name = 'Test Deal4', Account_Name__c = objAccount.Id, 
																	Status__c = 'Open'),
													new Deal__c(	Name = 'Test Deal5', Account_Name__c = objAccount.Id, 
																	Status__c = 'Open'),
													new Deal__c(	Name = 'Test Deal6', Account_Name__c = objAccount.Id, 
																	Status__c = 'Open'),
													new Deal__c(	Name = 'Test Deal7', Account_Name__c = objAccount.Id, 
																	Status__c = 'Open'),
													new Deal__c(	Name = 'Test Deal8', Account_Name__c = objAccount.Id, 
																	Status__c = 'Open'),
													new Deal__c(	Name = 'Test Deal9', Account_Name__c = objAccount.Id, 
																	Status__c = 'Open'),
                                                    new Deal__c(	Name = 'Test Deal10', Account_Name__c = objAccount.Id, 
																	Status__c = 'Open')																	
															};
		
		insert lstDeal;
		
	     // replace YOURPAGENAME with actual page name
		PageReference pageRef = Page.YOURPAGENAME;
		Test.setCurrentPage(pageRef);
		ApexPages.currentPage().getParameters().put('fullscreen','true');
		
		ApexPages.StandardController sc = new ApexPages.StandardController(objAccount);
		
		// now pass it to the extension
		DealList stdController = new DealList(sc);
		
		// verify if 10 rows returned
		system.assertEquals(10, stdController.noOfRecords);
		
		system.assertEquals(true, stdController.hasNext);
		system.assertEquals(false, stdController.hasPrevious);
		system.assertEquals(1, stdController.pageNumber);
		
		stdController.next();
		system.assertEquals(2, stdController.pageNumber);
		stdController.last();
		system.assertEquals(2, stdController.pageNumber);
		stdController.previous();
		system.assertEquals(2, stdController.pageNumber);
		stdController.first();
		system.assertEquals(1, stdController.pageNumber);
		
		// trun of fullscreen
		ApexPages.currentPage().getParameters().put('fullscreen','false');
		sc = new ApexPages.StandardController(objAccount);
		
		// now pass it to the extension
		stdController = new DealList(sc);
	}
}

Try this once

All Answers

Nayana KNayana K
@isTest
public class DealListTest
{
	static testMethod void testDealListPage() 
	{
	
		Account objAccount = new Account(Name = 'Test Acc');
		insert objAccount;
		
		/* Assuming Name is not an auto number here. Please populate all the required field value pairs.*/
		List<Deal__c> lstDeal = new List<Deal__c>{	new Deal__c(	Name = 'Test Deal1', Account_Name__c = objAccount.Id, 
																	Status__c = 'Open'),
													new Deal__c(	Name = 'Test Deal2', Account_Name__c = objAccount.Id, 
																	Status__c = 'Open'),
													new Deal__c(	Name = 'Test Deal3', Account_Name__c = objAccount.Id, 
																	Status__c = 'Open'),
													new Deal__c(	Name = 'Test Deal4', Account_Name__c = objAccount.Id, 
																	Status__c = 'Open'),
													new Deal__c(	Name = 'Test Deal5', Account_Name__c = objAccount.Id, 
																	Status__c = 'Open'),
													new Deal__c(	Name = 'Test Deal6', Account_Name__c = objAccount.Id, 
																	Status__c = 'Open'),
													new Deal__c(	Name = 'Test Deal7', Account_Name__c = objAccount.Id, 
																	Status__c = 'Open'),
													new Deal__c(	Name = 'Test Deal8', Account_Name__c = objAccount.Id, 
																	Status__c = 'Open'),
													new Deal__c(	Name = 'Test Deal9', Account_Name__c = objAccount.Id, 
																	Status__c = 'Open'),
                                                    new Deal__c(	Name = 'Test Deal10', Account_Name__c = objAccount.Id, 
																	Status__c = 'Open')																	
															};
		
		insert lstDeal;
		
	     // replace YOURPAGENAME with actual page name
		PageReference pageRef = Page.YOURPAGENAME;
		Test.setCurrentPage(pageRef);
		ApexPages.currentPage().getParameters().put('fullscreen','true');
		
		ApexPages.StandardController sc = new ApexPages.StandardController(objAccount);
		
		// now pass it to the extension
		DealList stdController = new DealList(sc);
		
		// verify if 10 rows returned
		system.assertEquals(10, stdController.noOfRecords);
		
		system.assertEquals(true, stdController.hasNext());
		system.assertEquals(false, stdController.hasPrevious());
		system.assertEquals(1, stdController.pageNumber);
		
		stdController.next();
		system.assertEquals(2, stdController.pageNumber);
		stdController.last();
		system.assertEquals(2, stdController.pageNumber);
		stdController.previous();
		system.assertEquals(2, stdController.pageNumber);
		stdController.first();
		system.assertEquals(1, stdController.pageNumber);
		
		// trun of fullscreen
		ApexPages.currentPage().getParameters().put('fullscreen','false');
		sc = new ApexPages.StandardController(objAccount);
		
		// now pass it to the extension
		stdController = new DealList(sc);
	}
}

 
Robert RobinsonRobert Robinson
Thank you so much for the code. After I enter the name of the VF page (AcctDealRelatedList), I get a compile error:
Method does not exist or incorrect signature: [DealList].hasNext() at line 48 column 35. Not sure why. Thanks
Nayana KNayana K
@isTest
public class DealListTest
{
	static testMethod void testDealListPage() 
	{
	
		Account objAccount = new Account(Name = 'Test Acc');
		insert objAccount;
		
		/* Assuming Name is not an auto number here. Please populate all the required field value pairs.*/
		List<Deal__c> lstDeal = new List<Deal__c>{	new Deal__c(	Name = 'Test Deal1', Account_Name__c = objAccount.Id, 
																	Status__c = 'Open'),
													new Deal__c(	Name = 'Test Deal2', Account_Name__c = objAccount.Id, 
																	Status__c = 'Open'),
													new Deal__c(	Name = 'Test Deal3', Account_Name__c = objAccount.Id, 
																	Status__c = 'Open'),
													new Deal__c(	Name = 'Test Deal4', Account_Name__c = objAccount.Id, 
																	Status__c = 'Open'),
													new Deal__c(	Name = 'Test Deal5', Account_Name__c = objAccount.Id, 
																	Status__c = 'Open'),
													new Deal__c(	Name = 'Test Deal6', Account_Name__c = objAccount.Id, 
																	Status__c = 'Open'),
													new Deal__c(	Name = 'Test Deal7', Account_Name__c = objAccount.Id, 
																	Status__c = 'Open'),
													new Deal__c(	Name = 'Test Deal8', Account_Name__c = objAccount.Id, 
																	Status__c = 'Open'),
													new Deal__c(	Name = 'Test Deal9', Account_Name__c = objAccount.Id, 
																	Status__c = 'Open'),
                                                    new Deal__c(	Name = 'Test Deal10', Account_Name__c = objAccount.Id, 
																	Status__c = 'Open')																	
															};
		
		insert lstDeal;
		
	     // replace YOURPAGENAME with actual page name
		PageReference pageRef = Page.YOURPAGENAME;
		Test.setCurrentPage(pageRef);
		ApexPages.currentPage().getParameters().put('fullscreen','true');
		
		ApexPages.StandardController sc = new ApexPages.StandardController(objAccount);
		
		// now pass it to the extension
		DealList stdController = new DealList(sc);
		
		// verify if 10 rows returned
		system.assertEquals(10, stdController.noOfRecords);
		
		system.assertEquals(true, stdController.hasNext);
		system.assertEquals(false, stdController.hasPrevious);
		system.assertEquals(1, stdController.pageNumber);
		
		stdController.next();
		system.assertEquals(2, stdController.pageNumber);
		stdController.last();
		system.assertEquals(2, stdController.pageNumber);
		stdController.previous();
		system.assertEquals(2, stdController.pageNumber);
		stdController.first();
		system.assertEquals(1, stdController.pageNumber);
		
		// trun of fullscreen
		ApexPages.currentPage().getParameters().put('fullscreen','false');
		sc = new ApexPages.StandardController(objAccount);
		
		// now pass it to the extension
		stdController = new DealList(sc);
	}
}

Try this once
This was selected as the best answer
Robert RobinsonRobert Robinson
That did it. Thank you.
Robert RobinsonRobert Robinson
First pass gives me 19% coverage. (9/46 lines). A good start.
Robert RobinsonRobert Robinson
I see what is hanging me up. Not every account has a deal, so if I verify if 10 rows are returned, and moving randomly through the accounts in the test, I will get failures if i use this stanza:

// verify if 10 rows returned
46        system.assertEquals(10, stdController.noOfRecords);
47         
48        system.assertEquals(true, stdController.hasNext);
49        system.assertEquals(false, stdController.hasPrevious);
50        system.assertEquals(1, stdController.pageNumber);
51         
52        stdController.next();
53        system.assertEquals(2, stdController.pageNumber);
54        stdController.last();
55        system.assertEquals(2, stdController.pageNumber);
56        stdController.previous();
57        system.assertEquals(2, stdController.pageNumber);
58        stdController.first();
59        system.assertEquals(1, stdController.pageNumber);
 
Nayana KNayana K
Can you please let me know where the error is? I mean which assert is failing?
Nayana KNayana K
Lets forget about asserts for a moment. 
I have removed all assertEquals() except one here.

Can you try this and let me know how much is the coverage?
@isTest
public class DealListTest
{
	static testMethod void testDealListPage() 
	{
	
		Account objAccount = new Account(Name = 'Test Acc');
		insert objAccount;
		
		/* Assuming Name is not an auto number here. Please populate all the required field value pairs.*/
		List<Deal__c> lstDeal = new List<Deal__c>{	new Deal__c(	Name = 'Test Deal1', Account_Name__c = objAccount.Id, 
																	Status__c = 'Open'),
													new Deal__c(	Name = 'Test Deal2', Account_Name__c = objAccount.Id, 
																	Status__c = 'Open'),
													new Deal__c(	Name = 'Test Deal3', Account_Name__c = objAccount.Id, 
																	Status__c = 'Open'),
													new Deal__c(	Name = 'Test Deal4', Account_Name__c = objAccount.Id, 
																	Status__c = 'Open'),
													new Deal__c(	Name = 'Test Deal5', Account_Name__c = objAccount.Id, 
																	Status__c = 'Open'),
													new Deal__c(	Name = 'Test Deal6', Account_Name__c = objAccount.Id, 
																	Status__c = 'Open'),
													new Deal__c(	Name = 'Test Deal7', Account_Name__c = objAccount.Id, 
																	Status__c = 'Open'),
													new Deal__c(	Name = 'Test Deal8', Account_Name__c = objAccount.Id, 
																	Status__c = 'Open'),
													new Deal__c(	Name = 'Test Deal9', Account_Name__c = objAccount.Id, 
																	Status__c = 'Open'),
                                                    new Deal__c(	Name = 'Test Deal10', Account_Name__c = objAccount.Id, 
																	Status__c = 'Open')																	
															};
		
		insert lstDeal;
		
	     // replace YOURPAGENAME with actual page name
		PageReference pageRef = Page.YOURPAGENAME;
		Test.setCurrentPage(pageRef);
		ApexPages.currentPage().getParameters().put('fullscreen','true');
		
		ApexPages.StandardController sc = new ApexPages.StandardController(objAccount);
		
		// now pass it to the extension
		DealList stdController = new DealList(sc);
		
		// verify if 10 rows returned
		system.assertEquals(10, stdController.noOfRecords);
		Boolean blnHasNext = stdController.hasNext;
		Boolean blnHasPrevious = stdController.hasPrevious;
		
		stdController.next();
		
		stdController.last();
		
		stdController.previous();
		
		stdController.first();
		
		
		// trun of fullscreen
		ApexPages.currentPage().getParameters().put('fullscreen','false');
		sc = new ApexPages.StandardController(objAccount);
		
		// now pass it to the extension
		stdController = new DealList(sc);
	}
}

 
Robert RobinsonRobert Robinson
Yes, at line 46 (system.assertEquals(10, stdController.noOfRecords);)
The issue is that not all Accounts have Deals associated with them. This is a VF page that returns the list of Deals for an Account if they exist; if not, the list is blank which is what is expected. There may also only be 1 or 2 deals associated with an account, so the value of 10 as a test will likely fail against a randomly selected group of Accounts.
Robert RobinsonRobert Robinson
Yes, it still fails at line 46, because it is looking for a list of 10 rows in cases where 0 rows may exist for a selected account. If I remove the "verify if 10 rows returned" section, I get 19% coverage. The problem is that i cannot figure out how to turn the "10 rows" test into a conditional test (if the selected Account has no Deals, ignore, for example) 
Nayana KNayana K
In test class I have inserted 10 Deals with Status Open for the account which I passed as standard controller. So ideally it should be 10 records returned.

Can you put debug
system.debug('===No of record===='+stdController.noOfRecords);
before 
system.assertEquals(10, stdController.noOfRecords); 
line.

And check the output in debug logs.
Nayana KNayana K
[Select Name, Location__c, Asset_Type__c, Underwriter__c, Amount__c, Stage__c, Estimated_Close__c, Closing_Probability_Category__c        from Deal__c                     
where Account_Name__c = :controller.getId()                    
and Status__c = 'Open']  query should return 10 records as per the test data.
Robert RobinsonRobert Robinson
This is my error from the logs:
System.AssertException: Assertion Failed: Expected: 10, Actual: null
Nayana KNayana K
@isTest
public class DealListTest
{
	static testMethod void testDealListPage() 
	{
	
		Account objAccount = new Account(Name = 'Test Acc');
		insert objAccount;
		
		/* Assuming Name is not an auto number here. Please populate all the required field value pairs.*/
		List<Deal__c> lstDeal = new List<Deal__c>{	new Deal__c(	Name = 'Test Deal1', Account_Name__c = objAccount.Id, 
																	Status__c = 'Open'),
													new Deal__c(	Name = 'Test Deal2', Account_Name__c = objAccount.Id, 
																	Status__c = 'Open'),
													new Deal__c(	Name = 'Test Deal3', Account_Name__c = objAccount.Id, 
																	Status__c = 'Open'),
													new Deal__c(	Name = 'Test Deal4', Account_Name__c = objAccount.Id, 
																	Status__c = 'Open'),
													new Deal__c(	Name = 'Test Deal5', Account_Name__c = objAccount.Id, 
																	Status__c = 'Open'),
													new Deal__c(	Name = 'Test Deal6', Account_Name__c = objAccount.Id, 
																	Status__c = 'Open'),
													new Deal__c(	Name = 'Test Deal7', Account_Name__c = objAccount.Id, 
																	Status__c = 'Open'),
													new Deal__c(	Name = 'Test Deal8', Account_Name__c = objAccount.Id, 
																	Status__c = 'Open'),
													new Deal__c(	Name = 'Test Deal9', Account_Name__c = objAccount.Id, 
																	Status__c = 'Open'),
                                                    new Deal__c(	Name = 'Test Deal10', Account_Name__c = objAccount.Id, 
																	Status__c = 'Open')																	
															};
		
		insert lstDeal;
		
	     // replace YOURPAGENAME with actual page name
		PageReference pageRef = Page.YOURPAGENAME;
		Test.setCurrentPage(pageRef);
		ApexPages.currentPage().getParameters().put('fullscreen','true');
		
		ApexPages.StandardController sc = new ApexPages.StandardController(objAccount);
		
		// now pass it to the extension
		DealList stdController = new DealList(sc);
		
		ApexPages.StandardSetController setCon = stdController.deals;
		
		// verify if 10 rows returned
		system.assertEquals(10, stdController.noOfRecords);
		
		
        Boolean blnHasNext = stdController.hasNext;
        Boolean blnHasPrevious = stdController.hasPrevious;
		system.assertEquals(1, stdController.pageNumber);
		
		stdController.next();
		system.assertEquals(2, stdController.pageNumber);
		stdController.last();
		system.assertEquals(2, stdController.pageNumber);
		stdController.previous();
		system.assertEquals(2, stdController.pageNumber);
		stdController.first();
		system.assertEquals(1, stdController.pageNumber);
		
		// trun of fullscreen
		ApexPages.currentPage().getParameters().put('fullscreen','false');
		sc = new ApexPages.StandardController(objAccount);
		
		// now pass it to the extension
		stdController = new DealList(sc);
	}
}

I think I understood the mistake. Please try the above code now
Nayana KNayana K
This line is must in my code:
ApexPages.StandardSetController setCon = stdController.deals;

I had missed it.
Robert RobinsonRobert Robinson
Wow.
That made a big difference. 58% coverage now. The failure is now on line 56, col 1:"System.AssertException: Assertion Failed: Expected: 2, Actual: 1 "

Ln 56: system.assertEquals(2, stdController.pageNumber);  - after stdController.next();
Robert RobinsonRobert Robinson
By switching lines 56, 58 and 60, from 2 to 1, the test class passed and coverage increased to 76%. The only problem is that I believe that I have violated the spirit of the test class you created. 
Robert RobinsonRobert Robinson
In fact, the only code lines not covered by the Test are lines 70 - 81:
    public PageReference refreshPageSize() {
         deals.setPageSize(size);
         return null;
    }
    public void showAll(){
        redirectUrl = '/apex/AcctDealRelatedList?id='+controller.getId()+'&fullscreen=true';
    }
    public void saveDeals(){
        try {
            deals.save();
        } catch (Exception e) {
            ApexPages.addMessages(e);
Robert RobinsonRobert Robinson
Thank you so much for your patience in helping me through this. You have given me the prototype through which to study. I will do my best to pay it forward.
Nayana KNayana K
I think pagenumber will not change in test class. Can you please comment all the asserts after stdController.next() method
Robert RobinsonRobert Robinson
Yes. Passed with the same coverage (76%) as when I changed the 2 to 1 on those lines that I commented out. Everything but the last 11 lines are "code covered". Thank you.
Nayana KNayana K
Comment all assertEquals after next().

After stdController.first() and before // turn of fullscreen

Add these lines:
stdController.refreshPageSize();
stdController.showAll();
stdController.saveDeals();

 
Robert RobinsonRobert Robinson
Amazing. Passed, and all but the last 2 lines are code covered:
    } catch (Exception e) {
            ApexPages.addMessages(e);
Nayana KNayana K
Covering exception in this case can be tricky some times... I I am not sure it will work. But Lets try this :
static testMethod void testDealListPage() 
	{
	
		Account objAccount = new Account(Name = 'Test Acc');
		insert objAccount;
// replace YOURPAGENAME with actual page name
		PageReference pageRef = Page.YOURPAGENAME;
		Test.setCurrentPage(pageRef);
		ApexPages.currentPage().getParameters().put('fullscreen','true');
		
		ApexPages.StandardController sc = new ApexPages.StandardController(objAccount);
		
		// now pass it to the extension
		DealList stdController = new DealList(sc);

/*  If we call save now, there are 0 deal records.  So save() may throw execution so that will enter try catch block*/
stdController.save();
}

 Create another test method in the same class
Nayana KNayana K
I forgot to change the method name. Please change the test Method name to something else. Because it wont allow you to save the test class.
Robert RobinsonRobert Robinson
You threw me a scare before mentioning the method name change :-) . That was the final piece. Again, thank you for the patience. I have a lot to study now.
Nayana KNayana K
Did you get 100% coverage? 
I would recommend you to go through trialhead modules for further learning.
Its midnight here! Sleepy.  Bye Robert. Happy coding
Robert RobinsonRobert Robinson
Yes.
I am a trailhead believer myself. 44 badges so far; however, nothing beats the real life example.
Thank you again for the real life lesson. Good night.
Robert RobinsonRobert Robinson
One last question: on line 10, you mentioned "Assuming Name is not an Auto Number"...In a case where the name IS an auto number, what are your options: use another existing field? Create a new field for testing? Thanks.
Nayana KNayana K
In test class while inserting test data records, we have to populate all required fields. Standard field name is required but if it is autonumber then we won't populate it. Eg: if we insert opportunity record, then name is required but not for case record because name is autonumber in case.
Robert RobinsonRobert Robinson
Thank you for the clarification. Robert L Robinson Manager, Salesforce Application [cid:image002.jpg@01D0FB5B.BD9097F0] Welltower Inc. 4500 Dorr Street Toledo, Ohio 43615-4040 419.247.2860 (o) 419.699.2539 (m) rrobinson@welltower.com Please note my new welltower.com email address.