+ Start a Discussion
TheLearnerTheLearner 

improving the code coverage

HI Experts,
Could anyone improve the code coverage of this class, i mentioned the lines with @ which are not covering.
public with sharing class WPD_Schedule_4Controller {

        List<WPD_Condition__c> conditionList = new List<WPD_Condition__c>();
        List<WPD_Co_Ordinate__c> coOrdinateList = new List<WPD_Co_Ordinate__c>();
        List<WPD_Purchase_Order_Line_Item__c> coPOList = new List<WPD_Purchase_Order_Line_Item__c>();
        
        public WPD_Projects__c Proj;
        public WPD_Reinstatement__c Work;
        public WPD_Co_Ordinate__c coOrdinate;
        public WPD_Purchase_Orders__c poLineItems;
        public WPD_Post_Code__c postCodeRec;
        public boolean modulePresent = false;
    
        public WPD_Reinstatement__c getWork(){
            if (Work==null){
                Work= new WPD_Reinstatement__c();
            }
            return Work;        
         }
         public WPD_Projects__c getProject()
         {
            if (Proj==null){
                Proj = new WPD_Projects__c();
            }
            return Proj;
         }
         
       public List<WPD_Condition__c> getArrCondition()
       {
            //Add to collection only if empty, else if mandatory field error comes, it will keep adding same numbers on VF page
            if (conditionList.size()==0)
            {
               for (integer i=0; i<=12; i++)
               {
                      conditionList.add(new WPD_Condition__c());
               }
            }
            return conditionList;
       }
       
       public List<WPD_Co_Ordinate__c> getArrCoordinate()
       {
            //Add to collection only if empty, else if mandatory field error comes, it will keep adding same numbers on VF page
            if (coOrdinateList.size()==0)
            {
               for (integer i=1; i<=6; i++)
               {
                      coOrdinateList.add(new WPD_Co_Ordinate__c());
               }
            }
            return coOrdinateList;
       }
       
       public List<WPD_Purchase_Order_Line_Item__c> getArrPurchaseOrder()
       {
            //Add to collection only if empty, else if mandatory field error comes, it will keep adding same numbers on VF page
            if (coPOList.size()==0)
            {
               for (integer i=1; i<=20; i++)//CH03
               {
                      coPOList.add(new WPD_Purchase_Order_Line_Item__c());
               }
            }
            return coPOList;
       }
        
        public PageReference save() {
            //Create savepoint
            Savepoint sp;
            
            List<WPD_Projects__c> WPDProj = [select Id, Name  from WPD_Projects__c where Name =:Proj.Name];
            //CH04.Start
            Date estimatePlanDate = Date.newInstance(2014,10,31);
            System.debug('estimatePlanDate = '+estimatePlanDate);
            List<WPD_Contract__c> wpdContracts;
            if(Proj.Estimated_Project_Start_Date__c != null && Proj.Work_Type__c != null)
                 wpdContracts = new List<WPD_Contract__c>([SELECT Id,Name,Work_Type__c,End_Date__c FROM WPD_Contract__c WHERE Work_Type__c INCLUDES (:Proj.Work_Type__c) AND End_Date__c >=: Proj.Estimated_Project_Start_Date__c order by End_Date__c ASC limit 1 ]);//CH05
            else
                 wpdContracts = new List<WPD_Contract__c>();
                 
             System.debug((Proj.Estimated_Project_Start_Date__c >= estimatePlanDate)+','+wpdContracts.isEmpty());
            //CH04.End
                if(WPDProj.size() > 0)
                {
                    ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.ERROR,'You can not save as this would create a duplicate record with Work Instruction field value [' + proj.Name + '].');
                    ApexPages.addMessage(msg);
                    return NULL;
                }
                //CH02.Start
                else if((Proj.Work_Type__c == 'Planned' || Proj.Work_Type__c == 'Planned GSOS') && (Proj.Dig_Start_Date__c == null || Proj.Dig_End_Date__c == null)){
                    ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.ERROR,'Dig Start Date and Dig End Date are mandatory if work type is Planned or Planned GSOS');
                    ApexPages.addMessage(msg);
                    return NULL;                
                }//CH02.End //CH04.Start
                else if(Proj.Estimated_Project_Start_Date__c != null && estimatePlanDate >= Proj.Estimated_Project_Start_Date__c && !wpdContracts.isEmpty() && wpdContracts.size() > 1 ){
             @@@@@@@@@@@----Not covering.start---@@@@@@@@@@@@@@@@@@
                 ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.ERROR,'Combination of Work Type and Estimated Start date does not match one individual current Contract Number record');
                    ApexPages.addMessage(msg);
                    return NULL;
         @@@@@@@@@@--Not covering.End---@@@@@@@@@@@@@@@@@@@
                }else if(Proj.Estimated_Project_Start_Date__c != null && Proj.Estimated_Project_Start_Date__c >= estimatePlanDate && wpdContracts.isEmpty()){
                    ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.ERROR,'No Contract Number found with Work Type and End Date > Estimated Project Start Date.');
                    ApexPages.addMessage(msg);
                    return NULL;
                }else{//CH04.End
                     try{
                        sp = Database.setSavepoint();
                        if(Proj.Estimated_Project_Start_Date__c != null && estimatePlanDate <= Proj.Estimated_Project_Start_Date__c && !wpdContracts.isEmpty()){
                            Proj.Contract__c = wpdContracts.get(0).id;
                        }
                        Proj.Date_Received__c = Date.today();
                        insert Proj;
                         
                        work.WPD_Projects__c = Proj.Id;
                        work.Works_Start_Date__c = work.Estimated_Start__c;
                        work.Works_End_Date__c = work.Estimated_End__c;
                        insert work;
                         
                        //Save Co-ordinate data
                        for(integer i=0; i<6; i++){
                            if(coOrdinateList[i].Easting__c!=null || coOrdinateList[i].Northing__c!=null){
          @@@@@@@--Notcovering.start---@@@@@@@@@@@@@@@@@@@@@@
                            coOrdinateList[i].Work__c = Work.Id;
                                if(i==0){
                                    work.Eastings_Start__c=coOrdinateList[i].Easting__c;
                                    work.Northings_Start__c=coOrdinateList[i].Northing__c;
                                }else if(i==1){
                                    work.Eastings_End__c=coOrdinateList[i].Easting__c;
                                    work.Northings_End__c=coOrdinateList[i].Northing__c;
                                }
                            }
                        }
                        insert coOrdinateList;
                        update work;

                        for (integer i=0; i<20; i++){
                            if (coPOList[i].Module__c!=null)
                            {
                                modulePresent=true;
                            }
                        }
                        
                        if(modulePresent){
                            //Save Purchase Order
                            poLineItems = new WPD_Purchase_Orders__c();
                            poLineItems.WPD_Projects__c = Proj.Id;
                            poLineItems.Purchase_Order_No__c = Proj.Name;
                            poLineItems.Date_Received__c = Date.today();
                            
                            insert poLineItems;
                        
                            //Save Purchase Order Line Item records
                            for (integer i=0; i<20; i++){
                                if (coPOList[i].Module__c!=null)
                                {
                                    
                                    coPOList[i].PO_Number__c = poLineItems.Id;
                                    //coPOList[i].Ordered_Rate__c = coPOList[i].Module__r.Rate__c; //Populate Ordered Rate with Rate from Module object //CH02 commented this line
                                    ///coPOList[i].Category__c = 'Not Required'; //Default Category to ‘Not Required’
                                    ///coPOList[i].Authorisation__c = true;
                                    ///coPOList[i].PO_Item__c = '001';
                                }
                            }
                            
                            insert coPOList;
                        }
                        
                            
                        //CH02.Start //Create WPD Task Record
                        if(poLineItems != null){
                            WPD_Purchase_Orders__c PO = [select Purchase_Order_Value__c, Purchase_Order_Duration__c from WPD_Purchase_Orders__c where id=:poLineItems.id];
                            WPD_Task__c task = new WPD_Task__c();
                            task.WPD_Project_Work_Instruction__c = Proj.Id;
                            task.value__c = PO.Purchase_Order_Value__c;
                            task.Duration__c = PO.Purchase_Order_Duration__c; 
                            
                            insert task;
                            //CH02.End                        
                        }
                        PageReference SchPage = new PageReference('/' + Proj.Id); //Redirect to the project record created
                        SchPage.setRedirect(true); 
                        return SchPage; 
    @@@@@@---Not covering.End---@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
                    }catch(Exception ex){
                        Database.rollback(sp);
                        Proj = Proj.clone(false);
                        work = work.clone(false);
                        
                        List<WPD_Co_Ordinate__c> templstCoOrdinates = coOrdinateList.clone();
                        coOrdinateList.clear();
                        for(WPD_Co_Ordinate__c tmpCoordinate : templstCoOrdinates){
                            coOrdinateList.add(tmpCoordinate.clone(false));                                
                        }
                        
                        
                        ///ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.ERROR,String.valueOf(ex));
                        ///ApexPages.addMessage(msg);
                        ApexPages.addMessages(ex);
                        return NULL;
                    }
                }
            }

            //this is for rnd n debugging
            public PageReference cancel() {
                    PageReference SchPage1 = new PageReference('/home/home.jsp' );//ApexPages.currentPage();
                    return SchPage1;
            }
    }


Test class:

@isTest

private with sharing class WPD_Schedule_4ControllerTest {

    //Covers the for loop in save method
    static TestMethod void WPD_Schedule_4Controller_1()
        {
            createContractRecord('03761');//CH01
            
            WPD_Depot__c depot = new WPD_Depot__c(Name='Test');
            insert depot;
            
            WPD_Schedule_4Controller s4 = new WPD_Schedule_4Controller();
            WPD_Projects__c proj = s4.getProject();
            WPD_Teams__c team = new WPD_Teams__c(name = 'Team');
            insert team;
            proj.name = 'Project';
            ///proj.Town__c='Town';
            proj.Notification_No__c='123';
            ///proj.Customer_Name__c='CustomerName';
            proj.Depots__c=depot.id;
            proj.Account__c='1234';
            proj.Product__c='5678';
            proj.Site_House_No__c='test house no';
            proj.Site_Street__c='test street';
            proj.Site_Town__c='test town';
            proj.Title__c='test title';
            proj.Estimated_Project_Start_Date__c = Date.today();
            //insert proj;
            WPD_Reinstatement__c work = s4.getWork();
            work.team_allocated__c = team.Id;
            //insert work;
            List<WPD_Co_Ordinate__c> cordinateList = s4.getArrCoordinate();
            //WPD_Co_Ordinate__c coordinate = new WPD_Co_Ordinate__c(work__c = work.id, Latitude__c = Double.valueOf('0.1452254'), Longitude__c = Double.valueOf('-0.1452545'), easting__c = '123456', northing__c = '125463');
            cordinateList[0].Easting__c='123456';
            cordinateList[0].Northing__c='125463';
            //cordinateList.add(coordinate);
            List<WPD_Purchase_Order_Line_Item__c> poList = s4.getArrPurchaseOrder();
            WPD_Modules__c TestModules = new WPD_Modules__c(Description__c='TestDescription', Rate__c=2.0, Unit__c='m', Quantity__c=2, Variation_Date__c=date.today(), Category__c='Betterment', Authorisation__c=true);
            insert TestModules;
            poList[0].Module__c=TestModules.id;
            /*WPD_Purchase_Orders__c POLI = new WPD_Purchase_Orders__c(WPD_Projects__c = proj.Id, Purchase_Order_Value__c = 2.0, Date_Received__c =  date.today());      
            insert POLI;
            WPD_Purchase_Order_Line_Item__c PO = new WPD_Purchase_Order_Line_Item__c(Project__c =proj.Id, PO_Number__c = POLI.Id, Quantity__c = 3.0, Module__c=TestModules.id);
            poList.add(PO);*/
            List<WPD_Condition__c> conditionList = s4.getArrCondition();
            conditionList[0].Condition__c = 'Test condition';
            
            s4.save();
            s4.cancel();
        }
        
    //covers NOT for loop but next IF condtions    
    static TestMethod void WPD_Schedule_4Controller_Test2()
        {
            createContractRecord('03751');//CH01
            
            WPD_Depot__c depot = new WPD_Depot__c(Name='Test');
            insert depot;

            WPD_Schedule_4Controller s4 = new WPD_Schedule_4Controller();
            WPD_Projects__c proj = s4.getProject();
            WPD_Teams__c team = new WPD_Teams__c(name = 'Test Team');
            insert team;
            proj.Account__c='1234';
            proj.Product__c='5678';
            proj.Site_House_No__c='test house no';
            proj.Site_Street__c='test street';
            proj.Site_Town__c='test town';
            proj.Title__c='test title';
            proj.name = 'Project';
            proj.Estimated_Project_Start_Date__c = Date.today();
            ///proj.Town__c='Town';
            proj.Notification_No__c='123';
            ///proj.Customer_Name__c='CustomerName';
            proj.Depots__c=depot.id;
            WPD_Reinstatement__c work = s4.getWork();
            work.team_allocated__c = team.Id;
            work.Notification_Type__c = 'Permit';
            List<WPD_Condition__c> conditionList = s4.getArrCondition();
            s4.save();
        }
    //covers the very first IF in the save method.    
    static TestMethod void WPD_Schedule_4Controller_Test3()
        {
            createContractRecord('03734');//CH01
            
            WPD_Depot__c depot = new WPD_Depot__c(Name='Test');
            insert depot;
            
            WPD_Schedule_4Controller s4 = new WPD_Schedule_4Controller();
            WPD_Projects__c proj = s4.getProject();
            WPD_Reinstatement__c work = s4.getWork();
            proj.name = 'Project';
            proj.Account__c='1234';
            proj.Product__c='5678';
            proj.Site_House_No__c='test house no';
            proj.Site_Street__c='test street';
            proj.Site_Town__c='test town';
            proj.Title__c='test title';
            ///proj.Town__c='Town';
            proj.Notification_No__c='123';
            proj.Estimated_Project_Start_Date__c = Date.today();
            ///proj.Customer_Name__c='CustomerName';
            proj.Depots__c=depot.id;
            WPD_Agent__c agent=new WPD_Agent__c();
            insert agent;
            
            WPD_Projects__c TestProject = new WPD_Projects__c(name = 'testProject', Account__c='123', Man_Unit__c='DY610', Product__c='123', title__c='aa',
                                instructions__c='aa', Site_house_no__c='aa',site_street__c='street', site_town__c='town', WPD_Agent__c=agent.id,Work_Pack_Seen__c=true,
                                Acceptance_Date__c=date.Today(), Notification_No__c='123',Date_Received__c=date.Today()); 
            insert TestProject;
            s4.save();
        }
        //CH01
        public static void createContractRecord(String nameVal){
            WPD_Contract__c toInsertCon =new WPD_Contract__c(Name = nameVal,Description__c = 'Test',End_Date__c = Date.today().addYears(1),Main_Contact__c = 'Test',Main_Depot__c = 'Test',Work_Type__c = 'Planned GSOS;Planned;Faults;Street Light Faults;Gas & Water Multi Utility');
            insert toInsertCon;
        } //CH01 
     //CH02.Start 
      static TestMethod void WPD_Schedule_4Controller_Test4(){
            WPD_Contract__c toInsertCon =new WPD_Contract__c(Name = '1234',Description__c = 'Test',End_Date__c = Date.today().addYears(1),Main_Contact__c = 'Test',Main_Depot__c = 'Test',Work_Type__c = 'Planned GSOS;Planned;Faults;Street Light Faults;Gas & Water Multi Utility');
            insert toInsertCon;
            
            WPD_Depot__c depot = new WPD_Depot__c(Name='Test');
            insert depot;
            
            WPD_Schedule_4Controller s4 = new WPD_Schedule_4Controller();
            WPD_Projects__c proj = s4.getProject();
            WPD_Reinstatement__c work = s4.getWork();
            proj.name = 'Project';
            proj.Account__c='1234';
            proj.Product__c='5678';
            proj.Site_House_No__c='test house no';
            proj.Site_Street__c='test street';
            proj.Site_Town__c='test town';
            proj.Title__c='test title';
            ///proj.Town__c='Town';
            proj.Notification_No__c='123';
            proj.Estimated_Project_Start_Date__c = Date.today()+1;
            Proj.Work_Type__c = 'Planned';
            ///proj.Customer_Name__c='CustomerName';
            proj.Depots__c=depot.id;
            Proj.Dig_Start_Date__c = null;
            WPD_Agent__c agent=new WPD_Agent__c();
            insert agent;
            
            WPD_Projects__c TestProject = new WPD_Projects__c(name = 'testProject', Account__c='123', Man_Unit__c='DY610', Product__c='123', title__c='aa',
                                instructions__c='aa', Site_house_no__c='aa',site_street__c='street', site_town__c='town', WPD_Agent__c=agent.id,Work_Pack_Seen__c=true,
                                Acceptance_Date__c=date.Today(), Notification_No__c='123',Date_Received__c=date.Today()); 
            insert TestProject;
            s4.save();
        }
      
       static TestMethod void WPD_Schedule_4Controller_Test5(){
            WPD_Contract__c toInsertCon =new WPD_Contract__c(Name = '1234',Description__c = 'Test',End_Date__c = Date.today().addYears(1),Main_Contact__c = 'Test',Main_Depot__c = 'Test',Work_Type__c = 'Planned GSOS;Planned;Faults;Street Light Faults;Gas & Water Multi Utility');
            insert toInsertCon;
            
            WPD_Depot__c depot = new WPD_Depot__c(Name='Test');
            insert depot;
           
            WPD_Schedule_4Controller s4 = new WPD_Schedule_4Controller();
            WPD_Projects__c proj = s4.getProject();
            WPD_Reinstatement__c work = s4.getWork();
            proj.name = 'Project';
            proj.Account__c='1234';
            proj.Product__c='5678';
            proj.Site_House_No__c='test house no';
            proj.Site_Street__c='test street';
            proj.Site_Town__c='test town';
            proj.Title__c='test title';
            ///proj.Town__c='Town';
            proj.Notification_No__c='123';
            proj.Estimated_Project_Start_Date__c = Date.newInstance(2014,10,03);
            Proj.Work_Type__c = 'Planned GSOS;Planned;Faults;Street Light Faults;Gas & Water Multi Utility';
            ///proj.Customer_Name__c='CustomerName';
            proj.Depots__c=depot.id;
            Proj.Dig_Start_Date__c = null;
            WPD_Agent__c agent=new WPD_Agent__c();
            insert agent;
            
            WPD_Projects__c TestProject = new WPD_Projects__c(name = 'testProject', Account__c='123', Man_Unit__c='DY610', Product__c='123', title__c='aa',
                                instructions__c='aa', Site_house_no__c='aa',site_street__c='street', site_town__c='town', WPD_Agent__c=agent.id,Work_Pack_Seen__c=true,
                                Acceptance_Date__c=date.Today(), Notification_No__c='123',Date_Received__c=date.Today()); 
            insert TestProject;
            s4.save();
        }
        static TestMethod void WPD_Schedule_4Controller_Test6(){
            WPD_Contract__c toInsertCon =new WPD_Contract__c(Name = '1234',Description__c = 'Test',End_Date__c = Date.today().addYears(1),Main_Contact__c = 'Test',Main_Depot__c = 'Test',Work_Type__c = 'Planned GSOS;Planned;Faults;Street Light Faults;Gas & Water Multi Utility');
            insert toInsertCon;
            
            WPD_Depot__c depot = new WPD_Depot__c(Name='Test');
            insert depot;
            WPD_Schedule_4Controller s4 = new WPD_Schedule_4Controller();
            WPD_Projects__c proj = s4.getProject();
            WPD_Reinstatement__c work = s4.getWork();
            proj.name = 'testProject';
            proj.Account__c='1234';
            proj.Product__c='5678';
            proj.Site_House_No__c='test house no';
            proj.Site_Street__c='test street';
            proj.Site_Town__c='test town';
            proj.Title__c='test title';
            ///proj.Town__c='Town';
            proj.Notification_No__c='123';
            proj.Estimated_Project_Start_Date__c = Date.newInstance(2014,10,03);
            Proj.Work_Type__c = 'Planned GSOS;Planned;Faults;Street Light Faults;Gas & Water Multi Utility';
            ///proj.Customer_Name__c='CustomerName';
            proj.Depots__c=depot.id;
            Proj.Dig_Start_Date__c = null;
            WPD_Agent__c agent=new WPD_Agent__c();
            insert agent;
             List<WPD_Co_Ordinate__c> cordinateList = s4.getArrCoordinate();
            //WPD_Co_Ordinate__c coordinate = new WPD_Co_Ordinate__c(work__c = work.id, Latitude__c = Double.valueOf('0.1452254'), Longitude__c = Double.valueOf('-0.1452545'), easting__c = '123456', northing__c = '125463');
            cordinateList[0].Easting__c='123456';
            cordinateList[0].Northing__c='125463';
           
            List<WPD_Purchase_Order_Line_Item__c> poList = s4.getArrPurchaseOrder();
            WPD_Modules__c TestModules = new WPD_Modules__c(Description__c='TestDescription', Rate__c=2.0, Unit__c='m', Quantity__c=2, Variation_Date__c=date.today(), Category__c='Betterment', Authorisation__c=true);
            insert TestModules;
            poList[0].Module__c=TestModules.id;
           
            List<WPD_Condition__c> conditionList = s4.getArrCondition();
            conditionList[0].Condition__c = 'Test condition';
            WPD_Projects__c TestProject = new WPD_Projects__c(name = 'testProject', Account__c='123', Man_Unit__c='DY610', Product__c='123', title__c='aa',
                                instructions__c='aa', Site_house_no__c='aa',site_street__c='street', site_town__c='town', WPD_Agent__c=agent.id,Work_Pack_Seen__c=true,
                                Acceptance_Date__c=date.Today(), Notification_No__c='123',Date_Received__c=date.Today()); 
            insert TestProject;
            s4.save();
        } 
              
}

 
James LoghryJames Loghry
TheLearner,

You have several logical branches in your code (if statements, for loops, try catches, etc).  Try simplifying your code by reducing these logical branches or removing them all together, and you'll find it's a lot easier to "cover your code" through unit tests.