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
Kris HankinsKris Hankins 

Test Class help for extension

I have an apex class I found on line that will allow me to restrict a visualforce page override to specific Profiles, which is what I want to do. I have edited both VF pages to what I need them to be and implementing the apex class along with the VF pages works exactly how I need it to in the sandbox. I obviously have to create a test class for code coverage before moving this over to production. I ahve also found several tutorials on creating apex test classes, but none seem to cover what I need. Any assistance I can get on this would be great. 

The apex class is:

public class overrideCon {

   String recordId;    

public overrideCon(ApexPages.StandardController

       controller) {recordId = controller.getId();}
 

public PageReference redirect() {

  Profile p = [select name from Profile where id =

               :UserInfo.getProfileId()];

  if ('*Custom: Sales Pilot'.equals(p.name)

     )

      {

       PageReference customPage =  Page.tabbedAccount;

       customPage.setRedirect(true);

       customPage.getParameters().put('id', recordId);

       return customPage;

      } else {

          return null; //otherwise stay on the same page 
     

      }
   }

}

The tabbedAccount VF page is below:

<apex:page standardController="Account"  
   
    action="{!If($Profile.Name != '*Custom: Sales Rep' || $Profile.Name !='*Custom: PSSR' 
        || $Profile.Name !='*Custom: Executive'  ,
        null,
        urlFor($Action.Account.Tab, $ObjectType.Account,
        null, true))}"


        showHeader="true"
        tabStyle="account" >
 <style>
     .activeTab {background-color: red; color:white;
      background-image:none}
      .inactiveTab { background-color: lightgrey; color:black;
      background-image:none}
 </style>
 
<apex:tabPanel switchType="client" selectedTab="tabdetails"
id="AccountTabPanel" tabClass="activeTab"
inactiveTabClass="inactiveTab">
<apex:tab label="Details" name="AccDetails" id="tabdetails">
<apex:detail relatedList="false" title="true"/>
</apex:tab>
<apex:tab label="Contacts" name="Contacts" id="tabContact">
<apex:relatedList subject="{!account}" list="contacts" />

</apex:tab>
<apex:tab label="Opportunities" name="Opportunities"
id="tabOpp">
<apex:relatedList subject="{!account}"
list="opportunities" />
</apex:tab>
<apex:tab label="Open Activities" name="OpenActivities"
id="tabOpenAct">
<apex:relatedList subject="{!account}"
list="OpenActivities" />
</apex:tab>
<apex:tab label="Notes and Attachments"
name="NotesAndAttachments" id="tabNoteAtt">
<apex:relatedList subject="{!account}"
list="CombinedAttachments" />
</apex:tab>
</apex:tabPanel>
</apex:page>

The standard Account page I will be using that contains the extension is:


<apex:page standardController="account" extensions="overrideCon" action="{!redirect}">

  <apex:detail />

</apex:page>


Best Answer chosen by Kris Hankins
James LoghryJames Loghry
@isTest
private class overrideConTest{

    static testmethod void testRedirectHappyPath(){
        Account a = new Account(Name='Test Account');
        insert a;

        //Insert a user to run as.  Assign it the Custom Sales Pilot profile id.
        User u = new User(
            //Lots of required fields go here.. google for an example.
            ProfileId = [Select Id From Profile Where Name='*Custom: Sales Pilot'].Id
        );
        insert u;

        Test.startTest();
        //Create a standard controller instance, and give it your inserted account.
        ApexPages.StandardController sctrl = new ApexPages.StandardController(a);

        //Instantiate your extension.
        overrideCon c = new overrideCon(sctrl);
   
        //Call your method.
        PageReference pageRef = c.redirect();
        Test.stopTest();

        //assert that your conditions were met.
        System.assertEquals(Page.tabbedAccount.getUrl(),pageRef.getUrl());
        System.assertEquals(a.Id,pageRef.getParameters().get('id'));
    }
 }


I wrote  a very generic example above for you, but the gist is:
  1. Create at least one test method for each public method in your controller / apex class.  Ideally, you'll have a single test method for each condition you have in your method.
  2. Create mock data so you dont have to rely on existing production data.  In your case, you'll have to create an account and assign it to the StandardController you pass in to your extension's constructor.
  3. Use Test.startTest / Test.stopTest around the method your testing to enforce it executes prior to your System assertion calls.
  4. Use several system asserts to test that your criteria is what you would expect.
Hope that helps.

All Answers

James LoghryJames Loghry
@isTest
private class overrideConTest{

    static testmethod void testRedirectHappyPath(){
        Account a = new Account(Name='Test Account');
        insert a;

        //Insert a user to run as.  Assign it the Custom Sales Pilot profile id.
        User u = new User(
            //Lots of required fields go here.. google for an example.
            ProfileId = [Select Id From Profile Where Name='*Custom: Sales Pilot'].Id
        );
        insert u;

        Test.startTest();
        //Create a standard controller instance, and give it your inserted account.
        ApexPages.StandardController sctrl = new ApexPages.StandardController(a);

        //Instantiate your extension.
        overrideCon c = new overrideCon(sctrl);
   
        //Call your method.
        PageReference pageRef = c.redirect();
        Test.stopTest();

        //assert that your conditions were met.
        System.assertEquals(Page.tabbedAccount.getUrl(),pageRef.getUrl());
        System.assertEquals(a.Id,pageRef.getParameters().get('id'));
    }
 }


I wrote  a very generic example above for you, but the gist is:
  1. Create at least one test method for each public method in your controller / apex class.  Ideally, you'll have a single test method for each condition you have in your method.
  2. Create mock data so you dont have to rely on existing production data.  In your case, you'll have to create an account and assign it to the StandardController you pass in to your extension's constructor.
  3. Use Test.startTest / Test.stopTest around the method your testing to enforce it executes prior to your System assertion calls.
  4. Use several system asserts to test that your criteria is what you would expect.
Hope that helps.
This was selected as the best answer
Kris HankinsKris Hankins
Thanks for the tip James. I added the fields for the user to be inserted and that works fine. I am getting a "attempt to dereference a null object in apex" error for line 28 column 1 of the test class now though. 

@isTest
private class overrideConTest{

    static testmethod void testRedirectHappyPath(){
        Account a = new Account(Name='Test Account');
        insert a;

        //Insert a user to run as.  Assign it the Custom Sales Pilot profile id.
        Profile p = [SELECT Id FROM Profile WHERE Name='*Custom: Sales Pilot']; 
      User u = new User(Alias = 'standus', Email='standardus@testorg.com', 
      EmailEncodingKey='UTF-8', LastName='Testuser', LanguageLocaleKey='en_US', 
      LocaleSidKey='en_US', ProfileId = p.Id, 
      TimeZoneSidKey='America/Los_Angeles', UserName='standardus@testorg.com');
        insert u;

        Test.startTest();
        //Create a standard controller instance, and give it your inserted account.
        ApexPages.StandardController sctrl = new ApexPages.StandardController(a);

        //Instantiate your extension.
        overrideCon c = new overrideCon(sctrl);
   
        //Call your method.
        PageReference pageRef = c.redirect();
        Test.stopTest();

        //assert that your conditions were met.
        System.assertEquals(Page.tabbedAccount.getUrl(),pageRef.getUrl());
        System.assertEquals(a.Id,pageRef.getParameters().get('id'));
    }
 }

Since System.assertEquals(Page.tabbedAccount.getUrl(),pageRef.getUrl()); for retrieving the UR, the page isn't being created? Or am I missing something that I should have added?
James LoghryJames Loghry
Forgot to add this, but you'll need to run the unit test as User u in order for it to detect the Custom Sales Pilot Profile.  Modify lines 16-25 in your previous example to the following:

Test.startTest();
PageReference pageRef = null;
System.runAs(u){
    //Create a standard controller instance, and give it your inserted account.
    ApexPages.StandardController sctrl = new ApexPages.StandardController(a);
    //Instantiate your extension.
    overrideCon c = new overrideCon(sctrl);
    //Call your method.
    pageRef = c.redirect();
}
Test.stopTest();


Kris HankinsKris Hankins
Thanks James.

I modified the code and still got an assertion error for line 28. If I change that line to System.assertNotEquals(Page.tabbedAccount.getUrl(),pageRef.getUrl()); the test passes and gives the overrideCon class 90% coverage (10/11).