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
Tim BauerTim Bauer 

Code Coverage for Simple Class

Hey Everyone,

I have a really simple controller I wrote to pass in values based on the user that's logged in, into a visual force page that loads as a home page component/layout. 

I don't have any experience with Salesforce and have no idea on how to write a TestClass that covers the code. I don't need 100%, just enough to deploy a slight change to the code.

Here's my controller class:

Public with sharing class iframeLinkController {

    Public String CurrentUserName {get;set;}
    Public String graburlnh { get; set; }    
    Public String graburl { get; set; }
    Public String grabhgt { get; set; }

Public iframeLinkController (){

    CurrentUserName = userinfo.getName();
    
    //testing tim bauer -- should be removed
    
    //salesperson individual dashboard - resin --make sure first line starts with "if" 
    if(CurrentUserName == 'Casey Taylor'){
        graburlnh = '/01Z50000000XORa?isdtp=nv';
        graburl = 'https://na3.salesforce.com/01Z50000000XORa';
        grabhgt = '2936px';
        }

    else if(CurrentUserName == 'Ryan Carter'){
        graburlnh = '/01Z50000000XORk?isdtp=nv';
        graburl = 'https://na3.salesforce.com/01Z50000000XORk';
        grabhgt = '2145px';
        }
    
    else if(CurrentUserName == 'Bryan Schutt'){
        graburlnh = '/01Z50000000XNZn?isdtp=nv';
        graburl = 'https://na3.salesforce.com/01Z50000000XNZn';
        grabhgt = '1871px';
        }
        
    else if(CurrentUserName == 'Scott Moros'){
        graburlnh = '/01Z50000000XOS4?isdtp=nv';
        graburl = 'https://na3.salesforce.com/01Z50000000XOS4';
        grabhgt = '1870px';
        }
        
    else if(CurrentUserName == 'Jonas Lee'){
        graburlnh = '/01Z50000000XOSJ?isdtp=nv';
        graburl = 'https://na3.salesforce.com/01Z50000000XOSJ';
        grabhgt = '2119px';
        }
        
    else if(CurrentUserName == 'Mark Powers'){
        graburlnh = '/01Z50000000XORu?isdtp=nv';
        graburl = 'https://na3.salesforce.com/01Z50000000XORu';
        grabhgt = '2090px';
        }
        
    //**************************************************************************************************
    //**************************************************************************************************
        
    //sales director dashboard - resin  
    else if(CurrentUserName == 'Luke Rains'){
        graburlnh = '/01Z50000000XOST?isdtp=nv';
        graburl = 'https://na3.salesforce.com/01Z50000000XOST';
        grabhgt = '3734px';
        }
        
    else if(CurrentUserName == 'Miguel Pena'){
        graburlnh = '/01Z50000000XOST?isdtp=nv';
        graburl = 'https://na3.salesforce.com/01Z50000000XOST';
        grabhgt = '3734px';
        }
        
    else if(CurrentUserName == 'Brad Phillips'){
        graburlnh = '/01Z50000000XOST?isdtp=nv';
        graburl = 'https://na3.salesforce.com/01Z50000000XOST';
        grabhgt = '3734px';
        }                

    //**************************************************************************************************
    //**************************************************************************************************
    
    //sales director dashboard - dustpro  
    else if(CurrentUserName == 'Marc McQuesten'){
        graburlnh = '/01Z50000000XOSY?isdtp=nv';
        graburl = 'https://na3.salesforce.com/01Z50000000XOSY';
        grabhgt = '2670px';
        }   

    else if(CurrentUserName == 'Chris Shaknis'){
        graburlnh = '/01Z50000000XOSY?isdtp=nv';
        graburl = 'https://na3.salesforce.com/01Z50000000XOSY';
        grabhgt = '2670px';
        } 
        
    else{
        graburlnh = '';
        graburl = '';
        grabhgt = '';
        }
    }
}

********************************************************************************************************************************************
********************************************************************************************************************************************
********************************************************************************************************************************************

Here's my test class that is garbage, most of it is commented out:

@isTest
public class iframeLinkControllerTests{
    
    public static testMethod void testMyController() {
        
        iframeLinkController controller = new iframeLinkController();
        PageReference pageRef = Page.NoClick_Page;
        Test.setCurrentPage(pageRef);
        
        //Verify that page fails without parameters
        //System.assertEquals('/apex/failure?error=noParam', nextPage);
    
        // Add parameters to page URL
        ApexPages.currentPage().getParameters().put('qp', 'yyyy');
      
        // Instantiate a new controller with all parameters in the page
        controller = new iframeLinkController(); 
        controller.CurrentUserName = 'Casey Taylor';
        controller.graburlnh = '/01Z50000000XORa?isdtp=nv';
        controller.graburl = 'https://na3.salesforce.com/01Z50000000XORa';
        controller.grabhgt = '2936px';

        // Verify that the success page displays
        //System.assertEquals('/apex/success', nextPage);
        //Lead[] leads = [select id, email from lead where Company = 'acme'];
        //System.assertEquals('firstlast@acme.com', leads[0].email);
    
    }
}

 
Best Answer chosen by Tim Bauer
AB TestAB Test
Hey Tim,

  What I understand from your question is that you are facing some issue to cover the class you have written. Please find my comments below.

ISSUES :
1. You have added parameters to the page in test class but nowhere are you checking the parameter in the constructor of the class.
2. You are setting controller variables CurrentUserName , graburlnh graburl etc after the initialisation of controller and the code you want to cover is inside constructor so it would never get those values.

SOLUTION:

As in your constructor your first line is --> CurrentUserName = userinfo.getName(); this would get the name of the current logged In user .

So In your test class you need to create new users with intended names (one you have specified in if condition) and run your constructor in this user's context. Please find below sample code. 
 
Profile profileObj = [SELECT Id FROM Profile WHERE Name='Standard User']; 
// use desired profile
User userObj = new User(Alias = 'standt', Email='standarduser@testorg.com', 
            EmailEncodingKey='UTF-8', FirstName='Casey',LastName='Taylor', LanguageLocaleKey='en_US', LocaleSidKey='en_US', ProfileId = profileObj.Id, 
            TimeZoneSidKey='America/Los_Angeles', UserName='standarduser@testorg.com');
// first name and last name should be the one you need to check
System.runAs(userObj) {
            // The following code runs as user 'userObj' 
            System.debug('Current User: ' + UserInfo.getUserName());
            System.debug('Current Profile: ' + UserInfo.getProfileId());
          // Run your constructor  inside this section      
 }

In the similar fashion , run the same constructor for all the users you have checked in your class and your code would be covered to 100 %
You can either update the name of the same user to all the values and run everytime the same user or create new user.
for creation of new user , please ensure that username is unique
. (Use of appending Math.random() or timestamp is encouraged).

This should solve your probem. If it does, please mark it as best answer. 
 
Just a suggestion : hardcoding IDs in your code is not a good practice as it may cause errors whenever you move your code from one org to other . please take care of the same.

Cheers

AB

All Answers

AB TestAB Test
Hey Tim,

  What I understand from your question is that you are facing some issue to cover the class you have written. Please find my comments below.

ISSUES :
1. You have added parameters to the page in test class but nowhere are you checking the parameter in the constructor of the class.
2. You are setting controller variables CurrentUserName , graburlnh graburl etc after the initialisation of controller and the code you want to cover is inside constructor so it would never get those values.

SOLUTION:

As in your constructor your first line is --> CurrentUserName = userinfo.getName(); this would get the name of the current logged In user .

So In your test class you need to create new users with intended names (one you have specified in if condition) and run your constructor in this user's context. Please find below sample code. 
 
Profile profileObj = [SELECT Id FROM Profile WHERE Name='Standard User']; 
// use desired profile
User userObj = new User(Alias = 'standt', Email='standarduser@testorg.com', 
            EmailEncodingKey='UTF-8', FirstName='Casey',LastName='Taylor', LanguageLocaleKey='en_US', LocaleSidKey='en_US', ProfileId = profileObj.Id, 
            TimeZoneSidKey='America/Los_Angeles', UserName='standarduser@testorg.com');
// first name and last name should be the one you need to check
System.runAs(userObj) {
            // The following code runs as user 'userObj' 
            System.debug('Current User: ' + UserInfo.getUserName());
            System.debug('Current Profile: ' + UserInfo.getProfileId());
          // Run your constructor  inside this section      
 }

In the similar fashion , run the same constructor for all the users you have checked in your class and your code would be covered to 100 %
You can either update the name of the same user to all the values and run everytime the same user or create new user.
for creation of new user , please ensure that username is unique
. (Use of appending Math.random() or timestamp is encouraged).

This should solve your probem. If it does, please mark it as best answer. 
 
Just a suggestion : hardcoding IDs in your code is not a good practice as it may cause errors whenever you move your code from one org to other . please take care of the same.

Cheers

AB
This was selected as the best answer
Amit Chaudhary 8Amit Chaudhary 8
Hi Tim,


Please try below test class. I hope you will get good code coverage but hardcoding IDs in your code is not a good practice
@isTest(seeAllData=true)
public class iframeLinkControllerTests{
    public static testMethod void testMyController() 
	{
		User usr;
		
		List<User> lstUser = [select userName,name from user where name ='Casey Taylor' ];
		
		if(lstUser.size() > 0 )
		{
			usr= lstUser[0];
			
			System.RunAs(usr)
			{
				iframeLinkController	obj = new iframeLinkController();	
			}
		}

		List<User> lstUser1 = [select userName,name from user where name ='Ryan Carter' ];
		
		if(lstUser1.size() > 0 )
		{
			usr= lstUser1[0];
			System.RunAs(usr)
			{
				iframeLinkController	obj1 = new iframeLinkController();	
			}
		}

		List<User> lstUser2 = [select userName,name from user where name ='Bryan Schutt' ];
		
		if(lstUser2.size() > 0 )
		{
			usr= lstUser2[0];
			System.RunAs(usr)
			{
				iframeLinkController	obj2 = new iframeLinkController();	
			}
		}

		List<User> lstUser3 = [select userName,name from user where name ='Scott Moros' ];
		if(lstUser3.size() > 0 )
		{
			usr= lstUser3[0];
			System.RunAs(usr)
			{
				iframeLinkController	obj3 = new iframeLinkController();	
			}
		}

		List<User> lstUser4 = [select userName,name from user where name ='Jonas Lee' ];
		if(lstUser4.size() > 0 )
		{
			usr= lstUser4[0];
			System.RunAs(usr)
			{
				iframeLinkController	obj4 = new iframeLinkController();	
			}
		}

		List<User> lstUser5 = [select userName,name from user where name ='Mark Powers' ];
		if(lstUser5.size() > 0 )
		{
			usr= lstUser5[0];
			System.RunAs(usr)
			{
				iframeLinkController	obj5 = new iframeLinkController();	
			}
		}
		
    }
}
Please check below post for more information on test classes
http://amitsalesforce.blogspot.in/2015/06/best-practice-for-test-classes-sample.html
Please follow below salesforce Best Practice for Test Classes :-

1. Test class must start with @isTest annotation if class class version is more than 25
2. Test environment support @testVisible , @testSetUp as well
3. Unit test is to test particular piece of code working properly or not .
4. Unit test method takes no argument ,commit no data to database ,send no email ,flagged with testMethod keyword .
5. To deploy to production at-least 75% code coverage is required
6. System.debug statement are not counted as a part of apex code limit.
7. Test method and test classes are not counted as a part of code limit
9. We should not focus on the  percentage of code coverage ,we should make sure that every use case should covered including positive, negative,bulk and single record .
Single Action -To verify that the the single record produces the correct an expected result .
Bulk action -Any apex record trigger ,class or extension must be invoked for 1-200 records .
Positive behavior : Test every expected behavior occurs through every expected permutation , i,e user filled out every correctly data and not go past the limit .
Negative Testcase :-Not to add future date , Not to specify negative amount.
Restricted User :-Test whether a user with restricted access used in your code .10. Test class should be annotated with @isTest .
11 . @isTest annotation with test method  is equivalent to testMethod keyword .
12. Test method should static and no void return type .
13. Test class and method default access is private ,no matter to add access specifier .
14. classes with @isTest annotation can't be a interface or enum .
15. Test method code can't be invoked by non test request .
16. Stating with salesforce API 28.0 test method can not reside inside non test classes .
17. @Testvisible annotation to make visible private methods inside test classes.
18. Test method can not be used to test web-service call out . Please use call out mock .
19. You can't  send email from test method.
20.User, profile, organization, AsyncApexjob, Corntrigger, RecordType, ApexClass, ApexComponent ,ApexPage we can access without (seeAllData=true) .
21. SeeAllData=true will not work for API 23 version eailer .
22. Accessing static resource test records in test class e,g List<Account> accList=Test.loadData(Account,SobjectType,'ResourceName').
23. Create TestFactory class with @isTest annotation to exclude from organization code size limit .
24. @testSetup to create test records once in a method  and use in every test method in the test class .
25. We can run unit test by using Salesforce Standard UI,Force.com IDE ,Console ,API.
26. Maximum number of test classes run per 24 hour of period is  not grater of 500 or 10 multiplication of test classes of your organization.
27. As apex runs in system mode so the permission and record sharing are not taken into account . So we need to use system.runAs to enforce record sharing .
28. System.runAs will not enforce user permission or field level permission .
29. Every test to runAs count against the total number of DML issued in the process .


Please let us know if this post will help you

Thanks
Amit Chaudhary