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
BillPowell__cBillPowell__c 

Custom Controller Test Class Help

Hey all, i'm slowly trying to learn apex and VF by adding my tweaks to code found elsewhere and understanding what it means (getting there!). However, i'm at a loss trying to figure out test classes, especially for a VF custom controller. 

Take a look let me know how i'd write a test class for this. Would I tell it to create a "Sample Order" record and populate the fields from the "Sample Order Line Items" object? My biggest problem is that I can understand the code (mostly), but can't write/regurgitate it :-( 
 
public class SampleController {
    public Sample_Order__c sampleOrder  { get; set; }
    public List<Sample_Order_Line_Items__c> sampleOrderLineItems     { get; set; }
    
    public SampleController() {
        sampleOrder             = new Sample_Order__c();
        sampleOrderLineItems    = new List<Sample_Order_Line_Items__c>{ new Sample_Order_Line_Items__c() };
    }
    
    public void addLineItem() {
        sampleOrderLineItems.add( new Sample_Order_Line_Items__c() );
    }
    
    public PageReference save() {
        INSERT sampleOrder;
        
        for( Sample_Order_Line_Items__c soli : sampleOrderLineItems ) {
            soli.Sample_Order__c = sampleOrder.Id;
        }
        
        INSERT sampleOrderLineItems;
        
        return new PageReference( '/' + sampleOrder.Id );
    }
    
    public PageReference cancel() {
        return new PageReference( '/home/home.jsp' );
    }
}

 
Raj VakatiRaj Vakati
Hi Bill , 

Please use this code and modify based on the data model and​ logic ​
@isTest
private class SampleController_UT {
	private static void testmethod testCasePositive(){
	Sample_Order__c  so = new Sample_Order__c ();
	so.Name ='test' ; 
	insert so ; 
	
	Sample_Order_Line_Items__c soLine = new Sample_Order_Line_Items__c();
	soLine.Sample_Order__c =so.Id ; 
	insert soLine ; 
	
	
	Sample_Order_Line_Items__c soLine1 = new Sample_Order_Line_Items__c();
	soLine1.Sample_Order__c =so.Id ; 
	insert soLine1 ; 
	
	SampleController  soClass = new SampleController () ; 
	soClass.addLineItem();
	soClass.save();
	soClass.cancel();
	
	}
	
}




 
Amit Chaudhary 8Amit Chaudhary 8
Hi
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

Pleasse check below post sample test class
1) 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 Sample_Order__c )
- Instantiate the Controlller-
- Execute a method/methods
- Verify the behaviour with asserts.

Please try below code in your code
@isTest
private class SampleControllerTest 
{
	private static void testmethod testMethod1()
	{
		
		SampleController  soObj = new SampleController();
		soObj.addLineItem();
		soObj.cancel();
		soObj.sampleOrder.name ='Test';
		// Add all required field for same
		
		
		try
		{
			soObj.save();
		}
		catch(Exception ee)
		{}
		// Add Assert here to check result
		
	}
	
}



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
BillPowell__cBillPowell__c
Do you need to add a name if the object records are autonumbered? 
Amit Chaudhary 8Amit Chaudhary 8
If Name is autonumber then no need to add Name
BillPowell__cBillPowell__c

I am completely lost on this, i'm sorry. Thank you all for your help. From what I gather, I need to enter field values for required fields so the test can run based on data entered against the code. However, since the controller spans 2 objects, im not sure which object i'm entering information for, and how to relate the data in required lookup fields. 

Here is what I have so far (not much). Ive also included the controller & VF page below what i've written so far. 

@isTest
private class SampleController_UT
{
    private static testmethod void testMethod1()
    {
        
        SampleController  soObj = new SampleController();
        soObj.addLineItem();
        soObj.cancel();
        soObj.Sample_Order__c = '???';  LOOKUP FIELD, HOW IS THIS ENTERED? 
        soObj.Quantity__c = 1;
        soObj.Project_name__c = '???'  LOOKUP FIELD, HOW IS THIS ENTERED?
        soObj.McGrory_Sales_Rep__c = '???';  LOOKUP FIELD, HOW IS THIS ENTERED?
        soObj.Ship_To__c = 'Customer';
        // Add all required field for same
        
        
        try
        {
            soObj.save();
        }
        catch(Exception ee)
        {}
        // Add Assert here to check result
        
    }
    
}
Here is the controller:
public class SampleController {
    public Sample_Order__c sampleOrder  { get; set; }
    public List<Sample_Order_Line_Items__c> sampleOrderLineItems     { get; set; }
    
    public SampleController() {
        sampleOrder             = new Sample_Order__c();
        sampleOrderLineItems    = new List<Sample_Order_Line_Items__c>{ new Sample_Order_Line_Items__c() };
    }
    
    public void addLineItem() {
        sampleOrderLineItems.add( new Sample_Order_Line_Items__c() );
    }
    
    public PageReference save() {
        INSERT sampleOrder;
        
        for( Sample_Order_Line_Items__c soli : sampleOrderLineItems ) {
            soli.Sample_Order__c = sampleOrder.Id;
        }
        
        INSERT sampleOrderLineItems;
        
        return new PageReference( '/' + sampleOrder.Id );
    }
    
    public PageReference cancel() {
        return new PageReference( '/home/home.jsp' );
    }
}
Here is the VF page
<apex:page controller="SampleController">
    <apex:form >
        <apex:sectionHeader title="Mass Create Sample Order Line Items"></apex:sectionHeader>
        <apex:pageBlock title="Sample Order Edit" mode="edit">

<!--SAMPLE ORDER RECORD SECTION & FIELDS-->  
            
			<apex:pageBlockSection title="Sample Order Information" collapsible="false" columns="2">              
                	<apex:inputField label="Project Name" value="{!sampleOrder.Project_Name__c}" required="true"/>
                	<apex:inputfield label="Order Status" value="{!sampleOrder.Status__c}" required="false"/>
                	<apex:inputField label="Sales Rep" value="{!sampleOrder.McGrory_Sales_Rep__c}" required="true" />
                	<apex:outputfield label="Order Date" value="{!sampleOrder.Request_Date__c}"/>
                	<apex:inputField label="Ship To" value="{!sampleOrder.Ship_To__c}" required="true"/>
                	<apex:inputfield label="Ship Date" value="{!sampleOrder.Ship_Date__c}" required="false"/>
                	<apex:inputField label="Notes" value="{!sampleOrder.Notes__c}" required="false"/> 
            </apex:pageBlockSection>
                        
            <apex:pageBlockSection title="Customer Information" collapsible="false" columns="2">
                	<apex:inputfield label="Company" value="{!sampleOrder.Company__c}" required="True"/>
                	<apex:outputfield label="Address" value="{!sampleOrder.Address__c}"/>
                	<apex:inputfield label="Contact" value="{!sampleOrder.Contact__c}" required="True"/>
               		<apex:inputfield label="Contact Phone" value="{!sampleOrder.Contact_Phone__c}"/>
                	<apex:inputField label="Contact Email" value="{!sampleOrder.Contact_Email__c}"/>
            </apex:pageBlockSection>
            
            <apex:pageBlockSection title="Alternate Contact Information - If Not Shipping To Sales Rep Or Customer" collapsible="false" columns="2">
                	<apex:inputfield label="Alternate Company" value="{!sampleOrder.Alternate_Company__c}" required="False"/>
                	<apex:inputfield label="Street Address" value="{!sampleOrder.Street_address__c}" required="False"/>
                	<apex:inputfield label="Alternate Contact" value="{!sampleOrder.Alternate_Contact__c}" required="False"/>
                	<apex:inputfield label="City" value="{!sampleOrder.City__c}" required="False"/>
                	<apex:inputfield label="Alternate Phone" value="{!sampleOrder.Alternate_Phone__c}" required="False"/>
                	<apex:inputfield label="State" value="{!sampleOrder.State__c}" required="False"/>
                	<apex:inputfield label="Alternate Email" value="{!sampleOrder.Alternate_Email__c}" required="False"/>
                	<apex:inputfield label="Zip/Postal Code" value="{!sampleOrder.Zip_Postal_Code__c}" required="False"/>               	              
            </apex:pageBlockSection>
            
<!--SAMPLE ORDER LINE ITEMS TABLE-->
            <apex:pageBlockSection title="Sample Order Line Items">
                <apex:pageBlockTable id="tblLineItems" value="{!sampleOrderLineItems}" var="soli">
                    <apex:column >
                        <apex:inputField value="{!soli.Quantity__c}"></apex:inputField>
                        <apex:facet name="header">
                            Quantity
                        </apex:facet>
                    </apex:column>
                    <apex:column >
                        <apex:inputField value="{!soli.Description__c}"></apex:inputField>
                        <apex:facet name="header">
                            Description
                        </apex:facet>
                    </apex:column>
                    <apex:column >
                        <apex:inputField value="{!soli.Width__c}"></apex:inputField>
                        <apex:facet name="header">
                            Width
                        </apex:facet>
                    </apex:column>
                    <apex:column >
                        <apex:inputField value="{!soli.Height__c}"></apex:inputField>
                        <apex:facet name="header">
                            Height
                        </apex:facet>
                    </apex:column>
                    <apex:column >
                        <apex:inputField value="{!soli.Product_Code__c}"></apex:inputField>
                        <apex:facet name="header">
                            Product Code
                        </apex:facet>
                    </apex:column>
                    <apex:facet name="footer">
                        <apex:commandButton value="Add Line" immediate="true" action="{!addLineItem}" rerender="tblLineItems"></apex:commandButton>
                    </apex:facet>
                </apex:pageBlockTable>
            </apex:pageBlockSection>
            <apex:pageBlockButtons >
                <apex:commandButton value="Save" action="{!save}"></apex:commandButton>
                <apex:commandButton value="Cancel" action="{!cancel}"></apex:commandButton>
            </apex:pageBlockButtons>
        </apex:pageBlock>
    </apex:form>
</apex:page>