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
tulasiram chtulasiram ch 

how to write test classes for visualforcepages please help me

Below is the code how can we write test class for this page with controller. Please help me
<apex:page controller="listViewsForContactRecords">
<apex:form >
            <apex:pageBlock >
           
            <apex:pageBlockTable value="{!accountsToDisplay}" var="acc" columns="2" id="pgtparent">
            <apex:column headerValue="AccountName" >
            <apex:commandLink value="{!acc.name}" action="{!MethodToCall}" rerender="pgbContacts" status="status">
            <apex:param value="{!acc.Id}" name="idForConts" assignTo="{!recid}"/>
            </apex:commandLink>
            </apex:column>
            <apex:column value="{!acc.Phone}"/>
            </apex:pageblockTable>
            </apex:pageBlock> 
    <apex:pageBlock title="Account Related Contacts"> 
       
    <apex:outputPanel id="pgbContacts">
    <apex:actionStatus startText="Please Wait Loading..." stopText="" id="status"></apex:actionStatus>
    <apex:pageblockTable value="{!conList }" var="cons">
    <apex:column headerValue="FirstName">
    <apex:inputText value="{!cons.FirstName}"/>
    </apex:column>
    <apex:column headerValue="LastName">
    <apex:inputText value="{!cons.LastName}"/>
    </apex:column>
    <apex:column >
    <apex:commandButton value="EditContact"/>
    </apex:column>
    </apex:pageblockTable>
    </apex:outputPanel> 
    </apex:pageBlock>
</apex:form>
</apex:page>
Controller:
public class listViewsForContactRecords {

    public list<contact> conList{get;set;}
    public string recid{get;set;}

    set<id> accIds = new set<id>();
    public list<account> accountsToDisplay{get;set;}
    public account getAcounts() {
        return null;
    }

public listViewsForContactRecords(){
accountsToDisplay = [select id, name, phone from account limit 10];

}
 public void MethodToCall() {
        conList = [select id, FirstName, LastName from contact where accountid=:recid];

    }
}
Best Answer chosen by tulasiram ch
Varun SinghVarun Singh
Hi @ tulasiram ch
I have  created test class  for controller and page
you will get 100%  coverage  from this.

Help url:http://www.aboveandbeyondcloud.com/apex-test-classes-best-practices/

Test class
 
@isTest
private class listViewsForContactRecordsTest {

    private static testMethod void TestMethod1() {
        Account a=new Account();
        a.name='Test';
        insert a;
       listViewsForContactRecords l=new listViewsForContactRecords();
       l.recid=a.id;
       l.MethodToCall();
       l.getAcounts();
}
}

If iformation is informative please choose my answer as best answer.
Thanks,
Varun
 

All Answers

Alain CabonAlain Cabon
Hi,

a) Using a generator of test class for test coverage (because you need to deploy in production very quickly):
Test Class Generator for Salesforce
This app helps you to generate test class for controller, trigger & batch .
 https://appexchange.salesforce.com/listingDetail?listingId=a0N3A00000EFozgUAD

b) Writing your own class of test for functional tests: 
 
   b.1) Find the buttons, links and their actions: here the action is on


       <apex:commandLink value="{!acc.name}" action="{!MethodToCall}" rerender="pgbContacts" status="status">

    b.2) Find the used data by the public getter/setter: here accounts ( controller )  and contacts ( response to the action ) 

 accountsToDisplay = [select id, name, phone from account limit 10];
 conList = [select id, FirstName, LastName from contact where accountid=:recid];

so you need to create a list of account and their contacts.

Utility tool: Salesforce-Test-Factory when you use a lot of columns : https://github.com/dhoechst/Salesforce-Test-Factory
 
    b.3) Find the parameters : none here.

   b.4) Salesforce documentation to put all together: it is a custom controller: https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_controller_error_handling.htm


c) Code generated with the Test Class Generator (need the package installed first because of tgen)  if you just want the 100% test coverage very quickly :  
@isTest
private class listViewsForContactRecords_Test{
    @testSetup
    static void setupTestData(){
        test.startTest();
        tgen.TestData.selectededFields.put('Account',new Set<string>{'Name'});
        //TestData.CreateData(ObjectName,Cascade,useAlreadyCreatedObj)
        Account account_Obj = (Account)tgen.TestData.CreateData('Account', false,false);
        Insert account_Obj;
        tgen.TestData.createdObjMap.put('Account',account_Obj.id);
        tgen.TestData.selectededFields.put('Contact',new Set<string>{'LastName','FirstName'});
        //TestData.CreateData(ObjectName,Cascade,useAlreadyCreatedObj)
        Contact contact_Obj = (Contact)tgen.TestData.CreateData('Contact', false,false);
        Insert contact_Obj;
        tgen.TestData.createdObjMap.put('Contact',contact_Obj.id);
        test.stopTest();
    }
    static testMethod void test_getAcounts_UseCase1(){
        List<Account> account_Obj = [SELECT Name from Account];
        System.assertEquals(true,account_Obj.size()>0);
        List<Contact> contact_Obj = [SELECT LastName,FirstName from Contact];
        System.assertEquals(true,contact_Obj.size()>0);
        listViewsForContactRecords obj01 = new listViewsForContactRecords();
        obj01.conList = contact_Obj;
        obj01.recid = 'test data';
        obj01.accountsToDisplay = account_Obj;
        obj01.getAcounts();
    }
    static testMethod void test_MethodToCall_UseCase1(){
        List<Account> account_Obj = [SELECT Name from Account];
        System.assertEquals(true,account_Obj.size()>0);
        List<Contact> contact_Obj = [SELECT LastName,FirstName from Contact];
        System.assertEquals(true,contact_Obj.size()>0);
        listViewsForContactRecords obj01 = new listViewsForContactRecords();
        obj01.conList = contact_Obj;
        obj01.recid = 'test data';
        obj01.accountsToDisplay = account_Obj;
        obj01.MethodToCall();
    }
    static testMethod void test_MethodToCall_UseCase2(){
        List<Account> account_Obj = [SELECT Name from Account];
        System.assertEquals(true,account_Obj.size()>0);
        List<Contact> contact_Obj = [SELECT LastName,FirstName from Contact];
        System.assertEquals(true,contact_Obj.size()>0);
        listViewsForContactRecords obj01 = new listViewsForContactRecords();
        obj01.conList = contact_Obj;
        obj01.recid = 'test data';
        obj01.accountsToDisplay = account_Obj;
        account_Obj[0].Name='Name669';
        Update account_Obj[0];
        contact_Obj[0].LastName='LastName694';
        contact_Obj[0].FirstName='FirstName437';
        Update contact_Obj[0];
        obj01.MethodToCall();
    }
}

Best regards
Alain
Alain CabonAlain Cabon
Test class generator (free); PROVIDER.  HEADQUARTERS Jaipur, Rajasthan, India

https://appexchange.salesforce.com/listingDetail?listingId=a0N3A00000EFozgUAD

1) Choose Class ( its parser will analyse everything )

User-added image
2) Build Data : basic but sufficient for your class

User-added image


3) See your test class

User-added image

and that's all. I run the result test class: 100% code coverage.

User-added image

User-added image

The data are not related between contact and account (basic data generated) but the coverage is 100% nevertheless.

Best regards
Alain
tulasiram chtulasiram ch
I think  we need to write the test classes right. What is all this tgen...
Alain CabonAlain Cabon
tgen is the namespace prefix for this great package. You have to use their package if you want to use their factory class otherwise you can use another free factory open-source here 

Utility tool: Salesforce-Test-Factory when you use a lot of columns : https://github.com/dhoechst/Salesforce-Test-Factory

Otherwise, you can create a list of account and contacts manually.

Given that the objects are generated by tgen, you can export them in JSON format and reuse them (if you want to delete all the references to tgen).

http://​https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_json_json.htm

Do you know how to create a list of accounts and contacts manually one by one without a factory (if not I can help you)?

Regards
Alain
Alain CabonAlain Cabon
Given that the objects are generated by tgen, you can export them in JSON format (String) and reuse them (if you want to delete all the references to tgen).
        
        tgen.TestData.selectededFields.put('Account',new Set<string>{'Name'});
        //TestData.CreateData(ObjectName,Cascade,useAlreadyCreatedObj)
        Account account_Obj = (Account)tgen.TestData.CreateData('Account', false,false);
        system.debug('account_Obj:' + Json.serialize(account_Obj));
        account_Obj = (Account) JSON.deserialize('{"attributes":{"type":"Account"},"Name":"Name737"}',Account.class);
        system.debug('name:' + account_Obj.name);

 Account account_Obj = (Account)tgen.TestData.CreateData('Account', false,false);
is equivalent to:
 Account account_Obj = (Account) JSON.deserialize('{"attributes":{"type":"Account"},"Name":"Name737"}',Account.class);

The sample above it is trivial but with a list with many objects and fields, this technique is the shortest for exporting and creating objects quickly.

Regards
Alain
Varun SinghVarun Singh
Hi @ tulasiram ch
I have  created test class  for controller and page
you will get 100%  coverage  from this.

Help url:http://www.aboveandbeyondcloud.com/apex-test-classes-best-practices/

Test class
 
@isTest
private class listViewsForContactRecordsTest {

    private static testMethod void TestMethod1() {
        Account a=new Account();
        a.name='Test';
        insert a;
       listViewsForContactRecords l=new listViewsForContactRecords();
       l.recid=a.id;
       l.MethodToCall();
       l.getAcounts();
}
}

If iformation is informative please choose my answer as best answer.
Thanks,
Varun
 
This was selected as the best answer
tulasiram chtulasiram ch
Varun Singh, i got 100% coverage. i don't know is that enough in real time. Give me the reply asap, i need to make it as best answer. Thank you!.
Varun SinghVarun Singh
Hi @ tulasiram ch

It is enough according to your controller.
i covered everything .you will get  any doubt  for  test  classes   i will help you.
When you will deploy it production these will no issue for this  class.
tulasiram chtulasiram ch
Thanks Varun, if u provide me your contact mail i will keep in touch with you. Thanks for every thing.
Varun SinghVarun Singh
your welcome 
spnvarun0121@gmail.com
i will try to solve your problem in the future if you.
tulasiram chtulasiram ch
Thanks a lot brother for your helping nature.