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
Joanne ButterfieldJoanne Butterfield 

Help with Apex Test

Hi All,
I have this great code ; however I am not a developer and having difficulties on writing the test code.
I have googled and search many test codes, but am lost and stuck. Any help would be much appreciated.
Thank you in advance!

Apex Class
public class TravelCalendar_Controller {



    public Boolean includeMyEvents {get;set;}

    public list<calEvent> events {get;set;}

    

    //The calendar plugin is expecting dates is a certain format. We can use this string to get it formated correctly

    String dtFormat = 'EEE, d MMM yyyy HH:mm:ss z';

    

    //constructor

    public TravelCalendar_Controller() {

        //Default showing my events to on

        includeMyEvents = false;

    }

    

    public PageReference pageLoad() {

        events = new list<calEvent>();

 
        //Get My Travel

        for(Travel__c mytrav : [select Id, Owner.FirstName, Owner.LastName, Name, Departure_Date__c, Return_Date__c, Owner_Territory__c from Travel__c where Approval_Status__c = 'Approved' and OwnerID = :UserInfo.getUserId() ]){

            DateTime startDT = myTrav.Departure_Date__c;

            DateTime endDT = myTrav.Return_Date__c;

            calEvent mytravEvent = new calEvent();

            

            mytravEvent.title = 'Trip:'+ ' ' + myTrav.Name+ ' ' + myTrav.Owner.FirstName+ ' ' + myTrav.Owner.LastName;

            mytravEvent.allDay = true;

            mytravEvent.startString = startDT.format(dtFormat);

            mytravEvent.endString = endDT.format(dtFormat);

            mytravEvent.url = '/' + myTrav.Id;

            mytravEvent.className = 'event-mytravel';

            events.add(mytravEvent);
    }
 
         //Get School Bus Travel

        for(Travel__c sbtrav : [select Id, Owner.FirstName, Owner.LastName, Name, Departure_Date__c, Return_Date__c, Owner_Territory__c from Travel__c where Approval_Status__c = 'Approved' and  Owner_Division__c = 'School Bus' and OwnerID != :UserInfo.getUserId() ]){

            DateTime startDT = sbTrav.Departure_Date__c;

            DateTime endDT = sbTrav.Return_Date__c;

            calEvent sbtravEvent = new calEvent();

            

            sbtravEvent.title = 'Trip:'+ ' ' + sbTrav.Name+ ' ' + sbTrav.Owner.FirstName+ ' ' + sbTrav.Owner.LastName;

            sbtravEvent.allDay = true;

            sbtravEvent.startString = startDT.format(dtFormat);

            sbtravEvent.endString = endDT.format(dtFormat);

            sbtravEvent.url = '/' + sbTrav.Id;

            sbtravEvent.className = 'event-sbtravel';

            events.add(sbtravEvent);

        }
 
         //Get Transit Travel

        for(Travel__c trtrav : [select Id, Owner.FirstName, Owner.LastName, Name, Departure_Date__c, Return_Date__c, Owner_Territory__c from Travel__c where Approval_Status__c = 'Approved' and  Owner_Division__c = 'Transit' and  OwnerID != :UserInfo.getUserId() ]){

            DateTime startDT = trTrav.Departure_Date__c;

            DateTime endDT = trTrav.Return_Date__c;

            calEvent trtravEvent = new calEvent();

            

            trtravEvent.title = 'Trip:'+ ' ' + trTrav.Name+ ' ' + trTrav.Owner.FirstName+ ' ' + trTrav.Owner.LastName;

            trtravEvent.allDay = true;

            trtravEvent.startString = startDT.format(dtFormat);

            trtravEvent.endString = endDT.format(dtFormat);

            trtravEvent.url = '/' + trTrav.Id;

            trtravEvent.className = 'event-trtravel';

            events.add(trtravEvent);

        }
        



//Get Other Travel

        for(Travel__c ottrav : [select Id, Owner.FirstName, Owner.LastName, Name, Departure_Date__c, Return_Date__c, Owner_Territory__c from Travel__c where Approval_Status__c = 'Approved' and  Owner_Division__c != 'School Bus' and  Owner_Division__c != 'Transit'and OwnerID != :UserInfo.getUserId() ]){

            DateTime startDT = otTrav.Departure_Date__c;

            DateTime endDT = otTrav.Return_Date__c;

            calEvent ottravEvent = new calEvent();

            

            ottravEvent.title = 'Trip:'+ ' ' + otTrav.Name+ ' ' + otTrav.Owner.FirstName+ ' ' + otTrav.Owner.LastName;

            ottravEvent.allDay = true;

            ottravEvent.startString = startDT.format(dtFormat);

            ottravEvent.endString = endDT.format(dtFormat);

            ottravEvent.url = '/' + otTrav.Id;

            ottravEvent.className = 'event-ottravel';

            events.add(ottravEvent);

        }

//Get my Events if we have selected the correct option

        if(includeMyEvents){

            for(Event evnt: [select Id, Subject, isAllDayEvent, StartDateTime, EndDateTime from Event where OwnerID = :UserInfo.getUserId()]){

                DateTime startDT = evnt.StartDateTime;

                DateTime endDT = evnt.EndDateTime;

                calEvent myEvent = new calEvent();

                

                myEvent.title = evnt.Subject;

                myEvent.allDay = evnt.isAllDayEvent;

                myEvent.startString = startDT.format(dtFormat);

                myEvent.endString = endDT.format(dtFormat);

                myEvent.url = '/' + evnt.Id;

                myEvent.className = 'event-personal';

                events.add(myEvent);

            }

        }

        return null;

    }

    

    public PageReference toggleMyEvents() {

        if(includeMyEvents){

            includeMyEvents = false;

        }

        else{

            includeMyEvents = true;

        }

        pageload();

        return null;

    }


    //Class to hold calendar event data

    public class calEvent{

        public String title {get;set;}

        public Boolean allDay {get;set;}

        public String startString {get;private set;}

        public String endString {get;private set;}

        public String url {get;set;}

        public String className {get;set;}

    }

}

VF Page
 
<apex:page controller="TravelCalendar_Controller" action="{!pageLoad}">
    
    <apex:relatedList list="TravelCalendar_Controller" />

    <link href="{!$Resource.fullCalendarCSS}" rel="stylesheet" />

    <link href="{!$Resource.fullCalendarPrintCSS}" rel="stylesheet" media="print" />
    
    <apex:includeScript value="{!$Resource.moment_min_js}"  />
    

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>

    <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>

    <script src="{!$Resource.fullCalendarMinJS}"></script>

    

    <script>

        //We need to wrap everything in a doc.ready function so that the code fires after the DOM is loaded

        $(document).ready(function() {   

            //Call the fullCallendar method. You can replace the '#calendar' with the ID of the dom element where you want the calendar to go. 

            $('#calendar').fullCalendar({

                header: {

                    left: 'prev,next today',

                    center: 'title',

                    right: 'month,agendaWeek,agendaDay'

                },

                editable: false,

                events:

                [

                    //At run time, this APEX Repeat will reneder the array elements for the events array

                    <apex:repeat value="{!events}" var="e">

                        {

                            title: "{!e.title}",

                            start: '{!e.startString}',

                            end: '{!e.endString}',

                            url: '{!e.url}',

                            allDay: {!e.allDay},

                            className: '{!e.className}'

                        },

                    </apex:repeat>

                ]

            });

            

        });

    

    </script>

    

    <!--some styling. Modify this to fit your needs-->

    <style>

        #cal-options {float:left;}

        #cal-legend { float:right;}

        #cal-legend ul {margin:0;padding:0;list-style:none;}

        #cal-legend ul li {margin:0;padding:5px;float:left;}

        #cal-legend ul li span {display:block; height:16px; width:16px; margin-right:4px; float:left; border-radius:4px;}

        #calendar {margin-top:20px;}

        #calendar a:hover {color:#fff !important;}

        

        .fc-event-inner {padding:3px;}

        .event-personal {background:#1797c0;border-color:#1797c0;}
        
        .event-mytravel {background:#00447b;border-color:#00447b;}
        
        .event-sbtravel {background:#FCB514;border-color:#FCB514;}
        
        .event-trtravel {background:#00A5DB;border-color:#00A5DB;}
        
        .event-ottravel {background:#676C74;border-color:#676C74;}
        

    </style>

    

    <apex:sectionHeader title="Travel Calendar"/>

    <apex:outputPanel id="calPanel">

        <apex:form >

            <div id="cal-options">

                <apex:commandButton value="{!IF(includeMyEvents,'Hide My Events','Show My Events')}" action="{!toggleMyEvents}"/>

            </div>

            <div id="cal-legend">

                <ul>
                    
                    <li><span class="event-mytravel"></span>My Travel</li>
                    
                    <li><span class="event-sbtravel"></span>School Bus Travel</li>
                    
                    <li><span class="event-trtravel"></span>Transit Travel</li>
                    
                    <li><span class="event-ottravel"></span>Other Travel</li>
                    
                   <li style="{!IF(includeMyEvents,'','display:none')}"><span class="event-personal"></span>My Events</li>

                </ul>

                <div style="clear:both;"><!--fix floats--></div>

            </div>

            <div style="clear:both;"><!--fix floats--></div>

            <div id="calendar"></div>

        </apex:form>

    </apex:outputPanel>

</apex:page>

Test Class attempt - not working.....
@ isTest
public class TestCase {

    static testMethod void testtravelController() {
        /**
         *  Create dummy objects for testing. Might need to add missing required fields
         */
 
    
   
          Travel__c trvl = new Travel__c (Name='Test Travel');
          insert trvl;


        Test.startTest();
            ApexPages.standardController sc = new ApexPages.standardController(trvl);
            TravelCalendar_Controller controller = new TravelCalendar_Controller(trvl);

            
        Test.stopTest();
    }

}

 
Best Answer chosen by Joanne Butterfield
James LoghryJames Loghry
The best thing I could tell you is to set up your data to match what your test is expecting.  As a devil's advocate, you should also set up data that could potentially break your code and test the boundary conditions.  However, for the positive tests, you have at least two scenarios in your code:
  1. The travel record is owned by the current user
  2. The travel record is owned by a school bus user
You should set up your records to test this accordingly.  For instance, you will need to create an additional user and an additional mock Travel__c record to test scenario 2.  This will help you get near 100% code coverage.

In addition to that, your test code was using an invalid constructor, and never calling the pageLoad method so I've fixed those in the example below as well.

Lastly, you should add System asserts to your code to verify that your code is working properly.  I'm not sure what conditions you're expecting, but again, see my example below for an idea on how you would use System.assert calls.

Good luck!
 
@ isTest
private class TestCase {
 
    static testMethod void testtravelController() {
       //
       User u = new User(
    
        );
        insert u;

        /**
         *  Create dummy objects for testing. Might need to add missing required fields
         */
          List<Travel__c> travels = new List<Travel__c>(){
              new Travel__c (
                  Name='Test Travel'
                  ,Departure_Date__c = Datetime.now()
                  ,Return_Date__c = Datetime.now()
                  ,Approval_Status__c = 'Approved'
              )
              ,new Travel__c(
                  Name='Test Travel 2'
                  ,Departure_Date__c = Datetime.now()
                  ,Return_Date__c = Datetime.now()
                  ,Approval_Status__c = 'Approved'
                 ,OwnerId = u.Id
                 ,Owner_Division__c = 'School Bus'
              )
          };
          insert travels;

        Test.startTest();
        TravelCalendar_Controller controller = new TravelCalendar_Controller();
        controller.pageLoad();
        Test.stopTest();

        //System.assertEquals(someValue,controller.someProperty);
        //System.assertNotEquals(true,controller.events.isEmpty());
        //System.assertEquals(someValue,controller.events.get(0).someProperty);
        //System.assertEquals(false,controller.includeMyEvents);
    }
}

 

All Answers

James LoghryJames Loghry
The best thing I could tell you is to set up your data to match what your test is expecting.  As a devil's advocate, you should also set up data that could potentially break your code and test the boundary conditions.  However, for the positive tests, you have at least two scenarios in your code:
  1. The travel record is owned by the current user
  2. The travel record is owned by a school bus user
You should set up your records to test this accordingly.  For instance, you will need to create an additional user and an additional mock Travel__c record to test scenario 2.  This will help you get near 100% code coverage.

In addition to that, your test code was using an invalid constructor, and never calling the pageLoad method so I've fixed those in the example below as well.

Lastly, you should add System asserts to your code to verify that your code is working properly.  I'm not sure what conditions you're expecting, but again, see my example below for an idea on how you would use System.assert calls.

Good luck!
 
@ isTest
private class TestCase {
 
    static testMethod void testtravelController() {
       //
       User u = new User(
    
        );
        insert u;

        /**
         *  Create dummy objects for testing. Might need to add missing required fields
         */
          List<Travel__c> travels = new List<Travel__c>(){
              new Travel__c (
                  Name='Test Travel'
                  ,Departure_Date__c = Datetime.now()
                  ,Return_Date__c = Datetime.now()
                  ,Approval_Status__c = 'Approved'
              )
              ,new Travel__c(
                  Name='Test Travel 2'
                  ,Departure_Date__c = Datetime.now()
                  ,Return_Date__c = Datetime.now()
                  ,Approval_Status__c = 'Approved'
                 ,OwnerId = u.Id
                 ,Owner_Division__c = 'School Bus'
              )
          };
          insert travels;

        Test.startTest();
        TravelCalendar_Controller controller = new TravelCalendar_Controller();
        controller.pageLoad();
        Test.stopTest();

        //System.assertEquals(someValue,controller.someProperty);
        //System.assertNotEquals(true,controller.events.isEmpty());
        //System.assertEquals(someValue,controller.events.get(0).someProperty);
        //System.assertEquals(false,controller.includeMyEvents);
    }
}

 
This was selected as the best answer
Joanne ButterfieldJoanne Butterfield
Hi James, Thank you so much for your help, I have been working on this all night and can't get the code coverage above 17%, and sorry but I don't understand the System Asserts. Would you be able to help me anymore. This is where I’m at now with the Test.
Thank you again!
 
@ isTest
private class TestCaseTravel {
 
    static testMethod void testtravelController() {
       //
       Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];
       User s = new User( Alias = 'standt', Email='standarduser@seon.com.com', 
      EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
      LocaleSidKey='en_US', ProfileId = p.Id, 
      TimeZoneSidKey='America/Los_Angeles', Division = 'School Bus', UserName='standarduser@seon.com');
    
       
        insert s;

User t = new User( Alias = 'standt', Email='standardusert@seon.com.com', 
      EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
      LocaleSidKey='en_US', ProfileId = p.Id, 
      TimeZoneSidKey='America/Los_Angeles', Division = 'Transit', UserName='standardusert@seon.com');
    
       
        insert t;

User o = new User( Alias = 'standt', Email='standarduser0@seon.com.com', 
      EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
      LocaleSidKey='en_US', ProfileId = p.Id, 
      TimeZoneSidKey='America/Los_Angeles', Division = 'Other', UserName='standarduser0@seon.com');
    
       
        insert o;

        /**
         *  Create dummy objects for testing. Might need to add missing required fields
         */
          List<Travel__c> travels = new List<Travel__c>{};
               new Travel__c (
                  Name='Test Travel'
                  ,Departure_Date__c = Date.today()
                  ,Return_Date__c = Date.today()
                  ,Approval_Status__c = 'Approved'
                  ,Travel_Purpose__c = 'test'
              )
              ;new Travel__c(
                  Name='Test Travel 2'
                  ,Departure_Date__c = Date.today()
                  ,Return_Date__c = Date.today()
                  ,Approval_Status__c = 'Approved'
                  ,Travel_Purpose__c = 'test'
                 ,OwnerId = s.Id
        )
              ;new Travel__c(
                  Name='Test Travel 3'
                  ,Departure_Date__c = Date.today()
                  ,Return_Date__c = Date.today()
                  ,Approval_Status__c = 'Approved'
                  ,Travel_Purpose__c = 'test'
                 ,OwnerId = t.Id
              )
              ;new Travel__c(
                  Name='Test Travel 4'
                  ,Departure_Date__c = Date.today()
                  ,Return_Date__c = Date.today()
                  ,Approval_Status__c = 'Approved'
                  ,Travel_Purpose__c = 'test'
                 ,OwnerId = o.Id
              
              
              )
          ;
          insert travels;


Event e = new Event();
        e.Subject = 'Test Event';
        e.Location = 'Test Location';
        e.Description = 'Test Description';
        e.StartDateTime = Datetime.now();
        e.EndDateTime = Datetime.now();
         
        insert e;
        

        Test.startTest();
        TravelCalendar_Controller controller = new TravelCalendar_Controller();
        controller.pageLoad();
        Test.stopTest();