+ Start a Discussion
mustafatopmustafatop 

How to test controller class?

I'm working on a job for entering multiple event records. I have used event standard field in my vf page but already exist validation rules haven't worked. Therefore I have created validation rules manually before insert process in save() method. And as a result, I can not create test method for validation rules in save() method.

 

How can I test save() method in following apex code?

<apex:page standardController="Event" extensions="AddMultipleEvent">
    <apex:form >
        <apex:outputPanel id="eventPage">
            <apex:pageMessages />
            <apex:pageBlock mode="edit">
                <apex:pageBlockSection title="SECTION1"/>
                
                <apex:repeat value="{!events2}" var="itr">                   
                    Assign To: <apex:inputField value="{!itr.OwnerId}"/>
                    Related To: <apex:inputField value="{!itr.WhatId}"/>
                    Name: <apex:inputField value="{!itr.WhoId}"/>
                </apex:repeat>

               <apex:pageBlockSection title="SECTION2"/>
                  <p align="center"><apex:commandButton action="{!save}" value=" Save " /></p>
                 
                          
                <apex:repeat value="{!events}" var="itr"> 
                    <br/><br/>     
                    
                    <table>            
                        <tr>        
                            <td><apex:inputfield value="{!itr.Subject}" id="subject"/></td><td>
                            <apex:inputfield value="{!itr.IsAllDayEvent}" id="day"/></td><td>
                            <apex:inputfield value="{!itr.StartDateTime}" id="start"/></td><td>
                            <apex:selectlist value="{!SelectedItem}" size="1">
                                <apex:selectOptions value="{!Items}"/>
                            </apex:selectlist></td><td>
                            <apex:inputfield value="{!itr.EndDateTime}" id="end"/></td><td>
                            <apex:selectlist value="{!SelectedItem2}" size="1">
                                <apex:selectOptions value="{!Items2}"/>
                            </apex:selectlist></td><td>
                            <apex:inputfield value="{!itr.Status__c}" id="status" /></td><td>
                            <apex:inputField value="{!itr.Type__c}" id="type"/></td><td>
                            <apex:inputField value="{!itr.Consultancy_Duration__c}" id="duration"/></td><td>
                            <apex:inputField value="{!itr.Project_Phase__c}" id="phase"/></td><td>
                            <apex:inputField value="{!itr.Location}" id="location"/></td><td>
                            <apex:inputField value="{!itr.Description}" id="description"/></td>
                        </tr>    
                    </table>
                                         
               </apex:repeat>
                                
                   <br/><br/>
                
                <p align="center"><apex:commandButton action="{!save}" value=" Save " /></p>
            </apex:pageBlock>

        </apex:outputPanel>

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

 

public class AddMultipleEvent{

    public List<Event> events{get; set;}
    
    public List<Event> events2{get; set;}
 
    public AddMultipleEvent(ApexPages.StandardController myController) {
        events2 = new List<Event>();
        events2.add(new Event());
        Integer i = 10;
        
        events = new List<Event>();
        for(Integer j=0; j<i; j+=1){
//            if(Test.isRunningTest()) events.add(new Event(startdatetime = datetime.now(),enddatetime = datetime.now()));
            events.add(new Event());
        }
    
    }
   
    public Datetime sDate(Integer i){
        Integer day = events.get(i).startdatetime.day();
        Integer month = events.get(i).startdatetime.month();
        Integer year = events.get(i).startdatetime.year();
        
        String[] s = getSelectedItem().split(':',2);
        Datetime dt = datetime.newInstance(year, month, day, Integer.valueOf(s[0]), Integer.valueOf(s[1]),0);
        return dt;
    }
    
    public Datetime eDate(Integer i){
        Integer day = events.get(i).enddatetime.day();
        Integer month = events.get(i).enddatetime.month();
        Integer year = events.get(i).enddatetime.year();
        
        String[] s = getSelectedItem2().split(':',22);
        Datetime dt = datetime.newInstance(year, month, day, Integer.valueOf(s[0]), Integer.valueOf(s[1]),0);
        return dt;
    }
     
    public Boolean C1(Datetime d1, Datetime d2){
        if(!(d1==null && d2==null)) return true; 
        return false;
    } 
    
    public PageReference save() {
        Boolean k = false;
        for(Integer i=0; i<events.size(); i+=1){
            if(C1(events.get(i).startdatetime, events.get(i).enddatetime)){
                k = true;
            }
            
        }
        if(!k){
            events.get(0).startdatetime.addError('Please enter a record');
            events.get(0).enddatetime.addError('Please enter a record');
            return null;
        }
        
        for(Integer i=0; i<events.size(); i+=1){
            events.get(i).ownerId = events2.get(0).ownerId;
            events.get(i).whatId= events2.get(0).whatId;
            events.get(i).whoId = events2.get(0).whoId ;
            
            if(events.get(i).startdatetime!=null)
                events.get(i).startdatetime= sDate(i);
            if(events.get(i).enddatetime!=null)
                events.get(i).enddatetime= eDate(i);
            
        }
        Boolean b = false;
        for(Integer i=0; i<events.size(); i+=1){
            if((events.get(i).Type__c+'')=='CB-Client Billable' || (events.get(i).Type__c+'').equals('CN-Client Non-Billable')){
               if(!(events.get(i).whatId+'').subString(0,3).equals('a0S')){
                    events.get(i).whatId.addError((i+1) + '.ROW: You cannot enter a site visit without a Project. Please link your site visit to a Project or contact with your manager.');
                    b = true;
               }
               if(events.get(i).whatId==null){
                    events.get(i).whatId.addError((i+1) + '.ROW: Site Visits should be related with a Project, Contract or Opportunity.');
                    b = true;
               }
            }
            if(events.get(i).subject==null){
                 events.get(i).subject.addError((i+1) + '.ROW: You must enter a value');
                 b = true;
            }
            if(events.get(i).startdatetime==null && events.get(i).enddatetime!=null){
                events.get(i).startdatetime.addError((i+1) + '.ROW: Please enter a start date');              
                return null;
            }
            if(events.get(i).startdatetime!=null && events.get(i).enddatetime==null){
                events.get(i).enddatetime.addError((i+1) + '.ROW: Please enter a end date');
                return null;
            }
        }
        
        if(b) return null;
        
        for(Integer i=0; i<events.size(); i+=1){
            if(events.get(i).startdatetime==null || events.get(i).enddatetime==null){
                events.remove(i);
                i = 0;
            }
        }
                
        insert events;     
        return new PageReference ('/00U/l');
     }
    
                
     String s = '09.00';
     String s2 = '09.00';
     
     public String getSelectedItem(){
          return s;
     }
     public void setSelectedItem(String s){
         this.s = s;
     }
     
     public String getSelectedItem2(){
          return s2;
     }
     public void setSelectedItem2(String s2){
         this.s2 = s2;
     }

     public List<SelectOption> getItems(){
            List<SelectOption> options = new list<SelectOption>();
            String mins = '30';
            for (Integer i = 0; i < 48; i++) 
            {
                mins        = (mins == '30') ? '00' : '30';
                Integer hrs = ((i*30) / 60);
                String hr   = (string.valueOf(hrs).length() == 1) ? '0' + string.valueOf(hrs) : string.valueOf(hrs);            

                String key = hr + ':' + mins;
   
                options.add(new SelectOption(key, key));
            }
            return options; 
                  
     }
     public List<SelectOption> getItems2(){
            List<SelectOption> options = new list<SelectOption>();
            String mins = '30';
            for (Integer i = 0; i < 48; i++) 
            {
                mins        = (mins == '30') ? '00' : '30';
                Integer hrs = ((i*30) / 60);
                String hr   = (string.valueOf(hrs).length() == 1) ? '0' + string.valueOf(hrs) : string.valueOf(hrs);            

                String key = hr + ':' + mins;
   
                options.add(new SelectOption(key, key));
            }
            return options; 
                  
     }
 
     public static testMethod void myTest(){
         AddMultipleEvent a = new AddMultipleEvent(null);
         System.assertEquals(a.save(),null);
         System.assertEquals(a.C1(Datetime.now(),Datetime.now()),true);
       
         System.assertEquals(a.getItems().get(0).getValue(),'00:00');
         System.assertEquals(a.getItems2().get(0).getValue(),'00:00');
         System.assertEquals(a.getSelectedItem(),'09.00');
         System.assertEquals(a.getSelectedItem2(),'09.00');
         a.setSelectedItem('00:00');
         a.setSelectedItem2('00:00');
         System.assertEquals(a.getSelectedItem(),'00:00');
         System.assertEquals(a.getSelectedItem2(),'00:00');
  //       System.assertEquals(a.sDate(Datetime.newInstance(2012,2,2)),'00:00');
         
         Event event = new Event(startdatetime = datetime.now(),enddatetime = datetime.now());
         PageReference pref = Page.addmultipleevent;
         pref.getParameters().put('id',event.id);
         Test.setCurrentPage(pref);
         
         
         ApexPages.StandardController con = new ApexPages.StandardController(event);
         AddMultipleEvent ade = new AddMultipleEvent(con);
         
     
         
    } 
   
    
}

 

All Answers

Sridhar BonagiriSridhar Bonagiri

Hi,

 

To test the save() method in Test class, Create a separte  test method in that create multiple event records in to a list and then try save that list, this save() method of the controller class will be called.

 

Regards,

Sridhar Bonagiri

mustafatopmustafatop

How to create mock event list in test method and after what should I test? I have used following code for test.

 

   
         Event event = new Event(startdatetime = datetime.now(),enddatetime = datetime.now());
         ApexPages.StandardController con = new ApexPages.StandardController(event);
         AddMultipleEvent ade = new AddMultipleEvent(con);
         System.assertEquals(ade.save(),null);

 

The code coverage shall not increase when I use above lines, because validation rules will not be tested.

Sridhar BonagiriSridhar Bonagiri

 


Hi,

 

Write one more method for the wrong testing that means do not give values to the fields and try to save the object like below. Then the code passes through your validation rules. I think this will solve you problem.

 

Regards,

Sridhar Bonagiri