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
Eric Anderson 54Eric Anderson 54 

test apex with extensions

So I have a Visualforce page that I have created that is related to a standard controller and also an extension to an 'Apex' controller. I've taken the 'Trailhead' training on testing an Apex class, but I can't seem to successfully apply what I learned in the Trailhead tutorial to my project and get there to not be syntax errors in my test code. I have only working on my first Visualforce/Apex project for a week now, so I'd sure welcome any suggestions anyone might have. The primary Methods that I am calling from the Visualforce Page are 'Save', 'Add' and 'Delete', so any help in any of those methods that I could then apply to the others would be greatly appreciated.

VISUALFORCE CODE:
<apex:page standardController="Request__c" extensions="TrController" >
    <!-- The following code will fix a problem with the calendar autospawning when the time entries are displayed. -->
    <script>
        function setFocusOnLoad(){ Coment.focus(); }
    </script>
   
    <!--Because we will be defining 'Input' fields, we must wrap our code in a 'Form' block. -->
    <apex:form id="Time_Entry_Form">
        <apex:pageBlock title="CDCR - Salesforce Time Reporting for Requests" id="Time_Entry_List">
           
            <!-- The following pageBlockButtons segment defines the two buttons that appear at the top of the Time entry form. -->
            <apex:pageBlockButtons id="Button_area">
                <!-- The following Button is defined in a more complicated fashion so that a parameter can be passed. -->
                <apex:commandLink >
                    <a href="javascript: CurrRequest('{!Request__c.Id}');" class="btn">New</a>               
                </apex:commandLink>
               
                <apex:commandLink >
                    <a href="javascript: SaveEntry();" class="btn">Save</a>               
                </apex:commandLink>

            </apex:pageBlockButtons>
           
             <!-- The following pageBlockTable segment defines the time entry rows that will be displayed. -->
            <apex:pageBlockTable value="{!TimeEntries}" var="entry" id="Entry_Table_List">
                <apex:column width="45" headerValue="Action">
                    <a href="javascript:if (window.confirm('Are you sure?')) DeleteEntry('{!entry.Id}');" style="font-weight:bold">Del</a>               
                </apex:column>   
                <apex:column width="70" headerValue="Activity">
                    <apex:inputField value="{!entry.Activity__c}"/>
                </apex:column>   
                <apex:column width="70" headerValue="Date Worked">
                    <apex:inputField value="{!entry.Date_Worked__c}"/>
                </apex:column>   
                <apex:column width="20" headerValue="Hours">
                    <apex:inputField value="{!entry.Hours_Worked__c}"/>
                </apex:column>   
                <apex:column width="20" headerValue="Worked">
                    <apex:inputField value="{!entry.Minutes_Worked__c}"/>
                </apex:column>   
                <apex:column headerValue="Work Description">
                    <apex:inputField style="width:100%" value="{!entry.Work_Description__c}" id="comment"/>
                </apex:column>
            </apex:pageBlockTable>
        </apex:pageBlock>
        <!-- This action block is executed based on the 'Delete' button being clicked on. -->
        <apex:actionFunction action="{!del}" name="DeleteEntry" reRender="Time_Entry_List">
            <apex:param name="EntryID" value="" assignTo="{!SelectedEntryID}"/>
        </apex:actionFunction>
       
         <!-- This action block is executed based on the 'New' button being clicked on. -->
        <apex:actionFunction action="{!add}" name="CurrRequest" reRender="Time_Entry_List">
            <apex:param name="EntryID" value="" assignTo="{!ReqID}"/>
        </apex:actionFunction>

         <!-- This action block is executed based on the 'Save' button being clicked on. -->
        <apex:actionFunction action="{!save}" name="SaveEntry" reRender="Time_Entry_List"/>
       
     </apex:form>
    <!-- The following script code is used in order to fix the problem with the calendar autospawning. -->
    <script>
        var Coment=document.getElementById('{!$Component.theForm.block.sec.item.comment}');
    </script>   
</apex:page>

CONTROLLER APEX CODE

public with sharing class TrController
{
    //This is the list for handling the group of time entries related to the parent object.
    public List<Time_Entry__c> TimeEntries {get;set;}
    //Used to get a hold of the entry record that is selected for deletion.
    public string SelectedEntryID {get;set;}
    //Used to get the parent request object ID from the Visual force page to the controller.
    public string ReqID {get;set;}
    public TrController(ApexPages.StandardController controller)
    {
        //Obtain the parent object Id from the the visualforce form.
        ReqId = Apexpages.currentPage().getparameters().get('Id');
        //Call the loaddata method to laod the time entries related to the parent object.
        LoadData();
     }
    public void LoadData()
    {
        //Obtain the first 15 bytes of the Parent Object ID to use for record selection.
        string RequestID = ReqId.substring(0, 15);
        //Load the related time entry records from the database.
        TimeEntries = [select id, Activity__c, Date_Worked__c, Hours_Worked__c, Minutes_Worked__c, Work_Description__c from Time_Entry__c WHERE Related_Object__c=:RequestID order by ID DESC];

    }
    public void save()
    {
        //Update the Salesforce database with the data entred.
        update TimeEntries;
    }
    public void add()
    {  
       //Obtain the first 15 bytes of the Parent Object ID to use for record identification.
        string RequestID = ReqId.substring(0, 15);
        //Build the default values to the new time entry record.
        Time_Entry__c entry = new Time_Entry__c(Activity__c='Research', Date_Worked__c=System.today(), Hours_Worked__c=' 0', Minutes_Worked__c='00', Related_Object__c=RequestID);
        //Insert the new default time entry row into the Salesforce database.
        Insert entry;
        //Call the method to reload the Visualforce list.
        LoadData();
    }
    public void del()
    {   
        //if we are missing the reference, then do nothing except return.
        if (SelectedEntryId == null)
        {
            return;
        }
        
        //If the record is within the collection, then delete it.
        Time_Entry__c tobeDeleted = null;
        for(Time_Entry__c a : TimeEntries)
        if (a.Id == SelectedEntryId)
            {
                tobeDeleted = a;
                break;
            }
        //If account record found then delete it.
        if (tobeDeleted != null)
            {
                Delete toBeDeleted;
            }
        //Refresh the list
        LoadData();

    }

}

Thank you in advance for your time.

Eric Anderson 
Best Answer chosen by Eric Anderson 54
Amit Chaudhary 8Amit Chaudhary 8
I will recommend you to start using trailhead to learn about test classes
1) https://trailhead.salesforce.com/modules/apex_testing

Also please check below post
1) https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_qs_test.htm
2) https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_testing_example.htm
3) http://amitsalesforce.blogspot.com/2015/06/best-practice-for-test-classes-sample.html

You write a test class for this the same way that you would any other:

- Set up some data for the Trigger to access (in this case it looks like Time_Entry__c object )
- Instantiate the controller -
- Execute a method/methods
- Verify the behaviour with asserts.

Please try below code
@isTest 
public class TrControllerTest 
{
	static testMethod void testMethod1() 
	{
	
		Insert the Related_Object__c here
		insert RelObj;
		
		Time_Entry__c te = new Time_Entry__c();
			te.Name ='Test';
			te.Related_Object__c = RelObj.id
			// Add all required field here
		insert te;
		

		Test.StartTest(); 
			Apexpages.currentPage().getparameters().put('id', String.valueOf(RelObj.Id));
			ApexPages.StandardController sc = new ApexPages.StandardController(RelObj);
			TrController testAccPlan = new TrController(sc);
			
			testAccPlan.save();
			testAccPlan.add();
			testAccPlan.del();
		
		Test.StopTest();
	}
}



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
 

All Answers

Alex EzhilarasanAlex Ezhilarasan
Hi Eric,

You want to run the page to test or trying to write test class for this controller?

-Alex 
Eric Anderson 54Eric Anderson 54
I'm sorry, I should have been more clear in my question. I am able to run my page just fine against the various methods of the controller. What I want to be able to do is develope a 'Test class' so that I can work through the 'Code Coverage' percentage for implementation.

Thank you in advance for your assistance.

- Eric
Alex EzhilarasanAlex Ezhilarasan
Hi Eric,

I can post you the solution, but you will not learn from that. So just give little push by referring the below.
https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_controller_error_handling.htm

If you have a tight deadline or struck at any place, just do let me know. I will help you.

Thanks,
Alex
Amit Chaudhary 8Amit Chaudhary 8
I will recommend you to start using trailhead to learn about test classes
1) https://trailhead.salesforce.com/modules/apex_testing

Also please check below post
1) https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_qs_test.htm
2) https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_testing_example.htm
3) http://amitsalesforce.blogspot.com/2015/06/best-practice-for-test-classes-sample.html

You write a test class for this the same way that you would any other:

- Set up some data for the Trigger to access (in this case it looks like Time_Entry__c object )
- Instantiate the controller -
- Execute a method/methods
- Verify the behaviour with asserts.

Please try below code
@isTest 
public class TrControllerTest 
{
	static testMethod void testMethod1() 
	{
	
		Insert the Related_Object__c here
		insert RelObj;
		
		Time_Entry__c te = new Time_Entry__c();
			te.Name ='Test';
			te.Related_Object__c = RelObj.id
			// Add all required field here
		insert te;
		

		Test.StartTest(); 
			Apexpages.currentPage().getparameters().put('id', String.valueOf(RelObj.Id));
			ApexPages.StandardController sc = new ApexPages.StandardController(RelObj);
			TrController testAccPlan = new TrController(sc);
			
			testAccPlan.save();
			testAccPlan.add();
			testAccPlan.del();
		
		Test.StopTest();
	}
}



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
 
This was selected as the best answer
Eric Anderson 54Eric Anderson 54
Just so everyone is aware, I went through the Trailhead material in regards to Testing before I opened this ticket. The problem with the Trailhead material, was it didn't really go through an example with an extension that is part of a visual force page. Based on a video that I went through a 2 + hour video (which just briefly mentioned the considerations having to do with a Visualforce page) on Youtube [https://youtu.be/n9amswhOxJw]. I'm also finding that my test class has compile errors like 'Time_Entry__c' does not exist for the 'PageReference' statement towards the top of the test class. The Test Class that I created looks like the following:

@isTest
public class TrControllerTestClass {
    @isTest private Static void testTrController()
    {
        PageReference pageRef = Page.Time_Entry__c;
        Test.setCurrentPage(pageRef);
        TrController calledController = TrController();
       
     //Initialize and prepare test data.
     //1. Execute Test of adding a row to the table.
        calledController.add();
     
     //2. Populate results
        List<String> Results = [SELECT Activity__c from Time_Entry__c order by ID DESC];
     
     //3. Report results
     System.assertEquals('Research', Results.Activity__c(1));
       
        calledController.LoadData();
    } 
}

I appreciate any assitance you might be able to provide.

Thanks!

 
Alex EzhilarasanAlex Ezhilarasan
Good Eric, this is what I want. Ok let's fix this test class.
 
@isTest
public class TrControllerTestClass {
    @isTest private Static void testTrController()
    {
        //Test record creation
        Request__c req = new Request__c(name = 'Test');//add required fields
        insert req;
        Time_Entry__c te = new Time_Entry__c(Activity__c='Research', Date_Worked__c=System.today(), Hours_Worked__c=' 0', Minutes_Worked__c='00', Related_Object__c=req.id);
        insert te;

        //Set the standard controller
        ApexPages.StandardController sc = new ApexPages.StandardController(req);
        TrController testTrCont = new TrController(sc);

        //Enter the Page Name. Not with __c. While launvhing this page check the url and add after /apex/    .Lets call this as 'PageName'
        PageReference pageRef = Page.PageName;
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;pageRef.getParameters().put('id', String.valueOf(req.Id));
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;Test.setCurrentPage(pageRef);
        
        testTrCont.add();
        testTrCont.save();

        //Set approriate record to testTrCont.SelectedEntryID value
        testTrCont.del();
    } 
}