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
Kiyana DunlockKiyana Dunlock 

Creates Test for Visual Force Page Controller

Hi I need help creaating a test class for a visula force page controller, below is the code:

VF Page:
<apex:page controller="AvailabilityReportSyndication" title="Syndication Availability Report">
    <apex:form id="frm">
        <apex:actionStatus id="status1" startText="Saving..." startStyle="font-size:18px"/>
        <apex:sectionHeader title="Availability Report Syndication"/>
        <apex:pageBlock >
            <apex:pageBlockButtons >
                <apex:commandButton value="Save" action="{!save}" reRender="frm" status="status1"/>
            </apex:pageBlockButtons>
            <table>
                <tr>
                    <h2><td width = "300px" bgcolor="grey"><B>Program: Program </B></td>
                    <td width = "100px" bgcolor="grey"><B>Units Available </B></td>
                    <td width = "100px" bgcolor="grey"><B>Schedule </B></td></h2>
                </tr>
            
                <apex:repeat value="{!programTeams}" var="obj">
                    <tr>
                        <td colspan="3" bgcolor="{!if(obj.team == 'Blue','Sky Blue',obj.team)}"><B>Program: Team: </B>{!obj.team}<B> ({!obj.tCount} Records)</B></td>
                        <apex:repeat value="{!obj.weeks}" var="w">
                            <tr>
                                <td colspan="3" bgcolor="cyan"><B>Week: </B>
                                    <apex:outputText value="{0,date,MM/dd/yyyy}">
                                        <apex:param value="{!w.week}"/>
                                    </apex:outputText>
                                    <B>({!w.wCount} Records)</B>
                                </td>
                                <apex:repeat value="{!w.schList}" var="s">
                                    <tr>
                                        <td><apex:outputField value="{!s.DealProgram__c}"/></td>
                                        <td align="center"><apex:inputField value="{!s.Units_Available__c}" style="width:50px" /></td>
                                        
                                        <td align="center">
                                            <a href="/{!s.id}" target="_blank">
                                                <apex:outputField value="{!s.Name}"/>
                                            </a>
                                        </td>
                                    </tr>
                                </apex:repeat>
                            </tr>
                        </apex:repeat>
                    </tr>
                </apex:repeat>
                <tr>
                    <td colspan="3" bgcolor="grey"><B>Grand Totals ({!grand} Records)</B></td>
                </tr>
            </table>

        </apex:pageBlock>
    </apex:form>
</apex:page>

Controller:
 
public class AvailabilityReportSyndication 
{
    public List<schedules__c> schedules;
    public List<programTeamModel> programTeams{get;set;}
    public Integer grand{get;set;}
    
    //Constructor definition
    public AvailabilityReportSyndication ()
    {
        getRecords();
    }
    private void getRecords() 
    {
    	programTeams = new List<programTeamModel>();
        schedules = [SELECT 
                        id, name, Week__c, Units_Available__c, Rate__c, DealProgram__c, Deal_Parent__c, 
                        Deal_Parent__r.Program__r.Team__c, DealBrand__c, Deal_Parent__r.Program__r.Cable_Synd__c 
                        FROM Schedules__c
                        WHERE Week__c >= LAST_N_DAYS:7 AND DealBrand__c = 'Availability' AND Deal_Parent__r.Program__r.Cable_Synd__c = 'Syndication' 
                        AND Deal_Parent__r.Program__r.Fixed_Inventory__c = false ORDER BY week__c LIMIT 1000
                    ];
        // 
        System.debug('######Records found==>'+schedules.size()+'###'+schedules);

        Map<String, Map<Date, List<Schedules__c>>> teamMap = new Map<String, Map<Date, List<Schedules__c>>>();
        for(Schedules__c sch: schedules)
        {
            if(sch.Deal_Parent__r.Program__r.Team__c != null)
            {
                Map<Date, List<Schedules__c>> weekMap = teamMap.get(sch.Deal_Parent__r.Program__r.Team__c);
                if(weekMap != null)
                {
                    List<Schedules__c> scheds = weekMap.get(sch.Week__c);
                    if(scheds != null)
                    {
                        scheds.add(sch);
                    }else
                    {
                        weekMap.put(sch.Week__c, new List<Schedules__c>{sch});
                    }
                }
                else
                {
                    weekMap = new Map<Date, List<Schedules__c>>();
                    weekMap.put(sch.Week__c, new List<Schedules__c>{sch});
                    teamMap.put(sch.Deal_Parent__r.Program__r.Team__c, weekMap);
                }
            }
        }
        grand = 0;
        for(String t : teamMap.keySet())
        {
            programTeamModel ptm = new programTeamModel();
            ptm.team = t;
            Map<Date, List<Schedules__c>> wMap = teamMap.get(t);
            
            List<Date> lstDates = new List<Date>();
            List<weekModel> wModelList = new List<weekModel>();
            integer i=0;
            lstDates.addAll(wMap.keySet());
            lstDates.sort();
            for(Date d : lstDates)
            {
              	weekModel wModel = new weekModel();
                List<Schedules__c> s = wMap.get(d);
                wModel.week = d;
                wModel.schList = s;
                wModelList.add(wModel);
                wModel.wCount = s.size();
                i += wModel.wCount;
            }
            ptm.weeks = wModelList;
            ptm.tCount = i;
            programTeams.add(ptm);
            grand += ptm.tCount;
        }
        
    }
    public void save() 
    {
        Set<Schedules__c> updatedSch = new Set<Schedules__c>();
        List<Schedules__c> updatedSchList = new List<Schedules__c>();
        for(programTeamModel p : programTeams)
        {
            List<weekModel> weekList = p.weeks;
            for(weekmodel w : weekList)
            {
                List<schedules__c> sList = w.schList;
                for(Schedules__c s : sList)
                {
                    updatedSch.add(s);
                }
            }
        }
        for(Schedules__c s:updatedSch)
        {
            updatedSchList.add(s);
        }
        upsert updatedSchList;
        system.debug('@@@@@@ Records saved####');
        getrecords();
    }
    class weekModel 
    {
        public integer wCount{get;set;}
        public Date week {get;set;}
        public List<Schedules__c> schList {get;set;}
        public weekModel()
        {
            schList = new List<Schedules__c>();
        }
    }
    class programTeamModel 
    {
        public Integer tCount{get;set;}
        public String team {set;get;}
        public List<weekModel> weeks {get;set;}
        public programTeamModel()
        {
            weeks = new List<weekModel>();
        }
    }
}

Please help thank you!
ANUTEJANUTEJ (Salesforce Developers) 
Hi Kiyana,

I found the below information from https://developer.salesforce.com/forums/?id=906F00000005JRuIAM where a person explained on the best practices that needs to be followed and what to be kept in mind in case if you are writing a test class.

I would recommend that you do some reading on testing [1] [2] [3] [4] to get a better understanding.  Each of your individual tests should only tests one specific portion of you class (ie a constructor test, redirPage test, etc).  You should also have both a postitive (everything works perfectly) and a negative (things are not right) test.

For testing controllers you should also read over this [5]

Each test should follow the following structure:
>>Setup of test data. This includes creation of any data needed by your class.  Account, Contacts etc
>>Starting the test. This is calling Test.startTest() to reset the governor limits
>>Calling your class / method
>>Stopping the test.This is calling Test.stopTest() to reset the governor limits and allow for any async jobs to finish
>>Asserting that your changes have worked
​         > If you have inserted/updated/deleted data, you need to query for the updates
         > Run System.assert, System.assertEquals, System.assertNotEquals to verify that you got the correct data back

[1] http://www.sfdc99.com/2013/05/14/how-to-write-a-test-class/
[2] http://pcon.github.io/presentations/testing/
[3] http://blog.deadlypenguin.com/blog/2014/07/23/intro-to-apex-auto-converting-leads-in-a-trigger/
[4] http://blog.deadlypenguin.com/blog/testing/strategies/
[5] https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_controller_error_handling.htm>


I hope this helps and in case if it does can you please choose this as the best answer so that it can be used by others in the future.

Regards,
Anutej