+ Start a Discussion
Nick KeehanNick Keehan 

How to build a test class for Account Search Page with Output Link.

Hi Guys.

Hoping someone can point me in the right direction for a Apex test to test a VF page and controller that basically searches for an account, then a Output link url goes to the customer edit page. I am relitively new to apex and cant get anything above 5% coverage with major editing of the apex class. 

An acacount number is entered into one of two fields, the page searches for accounts with that reference and rerenders the page, the page block table provides the account to be selected which is an output link the customer edit page.

Any suggestions/help would be really apreciated.

VF Page
<apex:page extensions="CreatingWizard2" standardController="Account" showHeader="false" sidebar="false" standardStylesheets="false" >
<html xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">    
<div class="slds"> 


<div class="slds-box slds-theme--alt-inverse">
  <p>
    <strong>Salesforce Step 1</strong> - Search/Create Customer</p>
</div>


 
<head>
  <title>Salesforce Lightning Design System Trailhead Module</title>
<apex:stylesheet value="/resource/SLDS0102/assets/styles/salesforce-lightning-design-system-ltng.css"/>
</head>   



<apex:form >


<fieldset class="slds-box slds-theme--default slds-container--end">
<legend id="newaccountform" class="slds-text-heading--medium slds-p-vertical--medium">Existing Customer Account Search</legend>  
<apex:pageMessages id="showmsg"></apex:pageMessages>

         <div class="slds-p-around--x-large">
         <div class="slds-form-element">            
         <label class="slds-form-element__label">TP2 Billing Account Number</label>
         <div class="slds-form-element__control">
         <apex:inputText value="{!searchstring2}" styleclass="slds-input"/>
         </div>
         <apex:commandButton action="{!search3}" value="Search TP2" styleClass="slds-button slds-button--brand slds-m-top--medium"/>  

</div></div>
<div class="slds-p-around--x-large">
      <div class="slds-form-element">            
        <label class="slds-form-element__label">Clarify Billing Account ID</label>
                <div class="slds-form-element__control">
          <apex:inputText value="{!searchstring}" styleclass="slds-input"/>
        </div>

<apex:commandButton action="{!search2}" value="Search Clarify" styleClass="slds-button slds-button--brand slds-m-top--medium"/>  
</div></div>
</fieldset>
 
 
 
<fieldset class="slds-box slds-theme--default slds-container--end">     
<legend id="newaccountform" class="slds-text-heading--medium slds-p-vertical--medium">Search Results</legend>
<apex:pageBlock rendered="{!or(searchstring != null, searchstring2 != null) }">  

   <apex:pageblockTable value="{!acc}" var="a">  
     <apex:column >  
      <apex:outputlink value="https://cs86.salesforce.com/{!a.id}/e?&00N7E000000dD7X=1">{!a.Name}</apex:outputlink>  
     </apex:column>  
     <apex:column value="{!a.phone}"/>  
     <apex:column value="{!a.id}"/>  
    </apex:pageBlockTable>   
  
   <apex:commandButton action="https://cs86.salesforce.com/001/e?retURL=%2F001%2Fo&RecordType=012200000000iKt&ent=Account&00N7E000000dD7X=1" value="Create a Customer" styleClass="slds-button slds-button--brand slds-m-top--medium"/>   
</apex:pageBlock>  

    <apex:actionFunction name="copyAndRerenderDepdPLFields" oncomplete="return copyDepdPLValues('{!$Component.DestID}' ,'{!$Component.SourceID}');" rerender="DestID" />
</fieldset> 


  
<script>
function copyContPLValues (DestContPListID,SourceContPListID) {
    document.getElementById(DestContPListID).value = document.getElementById(SourceContPListID).value;
    copyAndRerenderDepdPLFields();
}

function copyDepdPLValues (DestDepdPListID,SourceDepdPListID) {
    document.getElementById(DestDepdPListID).value = document.getElementById(SourceDepdPListID).value;
}
</script>

 

</apex:form>            
</div></html>
</apex:page>

Apex Class
public class CreatingWizard2{

public list <account> acc {get;set;}  
   public string searchstring {get;set;}  
      public string searchstring2 {get;set;} 
   public CreatingWizard2(ApexPages.StandardController controller) {  
   }  
   public void search2(){  
       if(searchstring2 == '' && searchstring == '')
       ApexPages.addmessage(new ApexPages.message(ApexPages.severity.FATAL,'Please enter an Account Number'));   
     string searchquery='select name,id,Clarify_Billing_Account_ID__c, phone, PersonMobilePhone from account where Clarify_Billing_Account_ID__c != null AND Clarify_Billing_Account_ID__c = :searchstring Limit 20';  
     acc= Database.query(searchquery);  
   }  
   
   public void search3(){  
       if(searchstring2 == '' && searchstring == '')
       ApexPages.addmessage(new ApexPages.message(ApexPages.severity.FATAL,'Please enter an Account Number'));   
     string searchquery='select name,id,Vodafone_FAB_Account_Number__c, phone, PersonMobilePhone from account where Vodafone_FAB_Account_Number__c != null AND Vodafone_FAB_Account_Number__c = :searchstring2 Limit 20';  
     acc= Database.query(searchquery);  
   }     
   
   
   public void clear(){  
   acc.clear();  
   }  
 

Account account;
 
 
public Account getAccount() {
if(account == null) account = new Account();
return account;
}

 
    public PageReference create() {
 
         PageReference opptyPage;
         opptyPage.setRedirect(true);
 
         return Page.resigns;
        } 
 

}


 
Best Answer chosen by Nick Keehan
Amit Chaudhary 8Amit Chaudhary 8
Try to call all method like below after data creation
Test.StartTest(); 
		
			ApexPages.StandardController sc = new ApexPages.StandardController(testAccount);
			CreatingWizard2 testAccPlan = new CreatingWizard2(sc);
			Account acc = testAccPlan.getAccount();
			testAccPlan.search2(); // 
			testAccPlan.search3();
			testAccPlan.create();
			testAccPlan.searchstring ='Test';
			testAccPlan.search2();

			testAccPlan.searchstring ='123';
			testAccPlan.search3();
			testAccPlan.clear();
			
			
		Test.StopTest();

Let us know if this will help you

All Answers

Amit Chaudhary 8Amit Chaudhary 8
Please check below post to learn about test classes
1) http://amitsalesforce.blogspot.com/search/label/Test%20Class
2) http://amitsalesforce.blogspot.com/2015/06/best-practice-for-test-classes-sample.html

Sample test class to start
@isTest 
public class CreatingWizard2Test 
{
	static testMethod void testMethod1() 
	{
		Account testAccount = new Account();
		testAccount.Name='Test Account' ;
		testAccount.Clarify_Billing_Account_ID__c ='Test'; // Add value according to data type
		testAccount.Vodafone_FAB_Account_Number__c ='123';
		insert testAccount;

		Test.StartTest(); 
		
			ApexPages.StandardController sc = new ApexPages.StandardController(testAccount);
			CreatingWizard2 testAccPlan = new CreatingWizard2(sc);
			Account acc = testAccPlan.getAccount();
			testAccPlan.searchstring ='Test';
			testAccPlan.search2();

			testAccPlan.searchstring ='123';
			testAccPlan.search3();
			testAccPlan.clear();
			
			
		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
Nick KeehanNick Keehan
Thanks Amit. Have installed the code coverage checker, looks great and very helpfull.

When using the test class you suggested, i only seem to get 73% coverage. We use PersonAccounts so i have attempted adding Record TypeId and Split out the name to first and last without any change to the coverage %.

Any tips on how to get the coverage a little higher? Had a read through above and cant see anything that would be stopping it?

Nick
Amit Chaudhary 8Amit Chaudhary 8
Try to call all method like below after data creation
Test.StartTest(); 
		
			ApexPages.StandardController sc = new ApexPages.StandardController(testAccount);
			CreatingWizard2 testAccPlan = new CreatingWizard2(sc);
			Account acc = testAccPlan.getAccount();
			testAccPlan.search2(); // 
			testAccPlan.search3();
			testAccPlan.create();
			testAccPlan.searchstring ='Test';
			testAccPlan.search2();

			testAccPlan.searchstring ='123';
			testAccPlan.search3();
			testAccPlan.clear();
			
			
		Test.StopTest();

Let us know if this will help you
This was selected as the best answer