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
Harvey JethroHarvey Jethro 

Issues with Apex Unit Test for nested for loop.

Hi all,
I'm currently having an issue with writing the test class for the attached try and catch. The code selects one or more parent records (Department__c) and creates detail records depending on the number of selected parent records. I've tried all my abilities and did a lot of online research but the nested for loop inside the try and catch is not covered. Please, see below for the code snippet. Your assistance will be appreciated.

        try{
            if(selectedBranchReport1.size() > 0){            
            List<Store__c> con1 = new List<store__c>();
                              
              for(Integer i = 0; i < selectedBranchReport1.size(); i++) {
               
                for(Integer j = 0; j < bLs.size(); j++)              
                {   
                   
                    bLs[j].Dpt__c = selectedBranchReport1[j].Id;
                    con1.add(bLs[j]);
                   
                }
               }
                   if(con1 != null){
                    upsert bLs;
                                   
Steven NsubugaSteven Nsubuga
If the nested for loop inside the try and catch is not covered, it is because selectedBranchReport1.size() = 0. There are no records in selectedBranchReport1, make sure that you created the necessary test records 
Harvey JethroHarvey Jethro
Thanks @Steven, I came up with the below but it is not working. Thanks for your help


@isTest 
private class testDepartment {
   
   public static void testTry(List<Department__c> Dept){
      
       Dept = new List<Department__c>();
        for(Integer i = 0 ;i<10;i++)
     {
        Dept.add(new Department__c(name='Test'+i)); 
     } 
      upsert Dept;  
      
       Store__c[] sList = new Store__c[] {}; 
        for(Integer x=0; x<10; x++){
        
        Store__c ct = new Store__c (Dpt__c = Dept[x].id );   
            sList.add(ct);
        }
        try{
            if(Dept.size() > 0) {             
            if(sList != null)
                      upsert sList;
            }
        }catch(Exception e){
          System.debug('something went wrong, exception: ' + e);  
    }  
  }


    static testMethod void TryCatchTest(){
        List<Department__c> accs = [select Id, name from Department__c where name Like 'Test%' Limit 10];
         List<Department__c> acs = [select Id, name from Department__c where name = 'flower'];
        Test.startTest();
        testDepartment.testTry(accs);
        testDepartment.testTry(acs);
        Test.stopTest();
   
    }
    }
 
Steven NsubugaSteven Nsubuga
Hi Harvey, please share the entire class that is being tested. 
Harvey JethroHarvey Jethro
Hi Steven, Thanks for your response The entire class:

public with sharing class formDeptNow {

    list<Department__c> dobjsuu{get;set;}
   public List<WrapBranchReport1> WrapBranchReportList1 {get; set; }
   public List<Department__c> selectedBranchReport1{get;set;}

   List<Store__c> bLs{get;set;}

    public  formDeptNow() {
        init();
          bLs = new List<Store__c>();
               AddRow();                        

       if(wrapBranchReportList1 ==null){
          WrapBranchReportList1 = new list<WrapBranchReport1>();
          for(Department__c a1:[Select name,  Unit__c,Budget__c, level__c,C1__c,C2__c,C3__c, C4__c FROM Department__c WHERE  level__c != null AND Unit__c != null AND   C1__c !=null And C2__c !=null AND  C3__c !=null And C4__c !=null ]){
           WrapBranchReportList1.add(new WrapBranchReport1(a1));          
           }
          selectedBranchReport1 = new List<Department__c>();               
        }
     }
 public void init() {
   dobjsuu = [Select name,  Unit__c, Budget__c, level__c, C1__c, C2__c,C3__c, C4__c FROM Department__c WHERE  level__c != null AND  C1__c !=null And C2__c !=null AND C3__c !=null AND C4__c !=null  Limit 8 ];
 }
 public PageReference step1() {
        return Page.Room1;
 }

 public PageReference step2a() {
        processSelected1();        
        return Page.Room2;
 }
  public PageReference AddRow() {
    bLs.add(new Store__c());
    return null;
 } 
 public void processSelected1(){
  selectedBranchReport1 = new list<Department__c>();     
    for(WrapBranchReport1 wra1 : WrapBranchReportList1){
       if(wra1.isSelected1==true){
         selectedBranchReport1.add(wra1.dp);
         }
     }
  }  
  public List <Store__c> getbLs() {
  if(bLs == null)    bLs = new List <Store__c>();
      return bLs;
   }
  public List<Department__c> getdobjsuu() {

   if(dobjsuu == null)   dobjsuu = new List<Department__c>();
      return dobjsuu;
 }

    public pageReference Cancel1(){
        return null;
    } 
  public pageReference Cancel2(){
    return Page.Room2.setRedirect(true);
   } 
public PageReference Save1(){
       upsert dobjsuu; 
        return null;
    }

 public PageReference Save() {
    upsert selectedBranchReport1;
     try{
          if(selectedBranchReport1.size() > 0){            
            List<Store__c> con1 = new List<store__c>();
              for(Integer i = 0; i < selectedBranchReport1.size(); i++) {
             for(Integer j = 0; j < bLs.size(); j++)              
                {   
                    bLs[j].Dpt__c = selectedBranchReport1[j].Id;
                    con1.add(bLs[j]);
                }
               }
                   if(con1 != null){
                    upsert bLs;
                }
            }      
     }                    

      catch(Exception e) {
            ApexPages.addMessage(new ApexPages.message(ApexPages.Severity.ERROR,e.getMessage()));
            return null;
        }

   return null;

 }

 public Pagereference doSaveAndNew() {  
         Save();
   String str = ApexPages.currentPage().getUrl().subStringAfter('/').substringBefore('?');
     return new PageReference('/apex/' + str).setRedirect(true);
}

   public class WrapBranchReport1 {    
    public Department__c dp {get;set;}
    public boolean isSelected1 {get;set;}
       public WrapBranchReport1( Department__c d){     
         dp = d;
         isSelected1=false;
       }
  }
 
   

     }
 
Steven NsubugaSteven Nsubuga
Test classes generally call methods in the class to be tested. See below
@isTest 
private class testDepartment {
   
	@isTest static void testformDeptNow(){
	  
		List<Department__c> Dept = new List<Department__c>();
		for(Integer i = 0 ;i<10;i++)
		{
			// I am assuming that C1__c, C2__c, C3__c and C4__c are text fields, if not, fix it
			Dept.add(new Department__c(name='Test'+i, level__c = 'level '+i, C1__c = 'c1'+i, C2__c= 'c2'+i, C3__c= 'c3'+i, C4__c= 'c4'+i)); 
		} 
		insert Dept;  

		Store__c[] sList = new Store__c[] {}; 
		for(Integer x=0; x<10; x++){
			Store__c ct = new Store__c (Dpt__c = Dept[x].id );   
			sList.add(ct);
		}
		insert sList;
	}
	
	formDeptNow formDept = new formDeptNow();
	
	System.assert(formDept.WrapBranchReportList1.size() > 0);
	
	formDept.WrapBranchReportList1[0].isSelected1 = true;
	formDept.processSelected1();
	
	System.assert(formDept.getbLs().size() > 0);
	
	System.assert(formDept.getdobjsuu().size() > 0);
	
	formDept.doSaveAndNew();
	
	formDept.Cancel1();
	
	formDept.Cancel2();
	
	formDept.Save1();
	
	formDept.step1();
	
	formDept.step2a();
}


 
Harvey JethroHarvey Jethro
I really appreciate your help. I made some changes to your test class because I was getting "System.AssertException: Assertion Failed: Error" 
however, it test did not cover the try and catch. The code coverage is 71 %

I'll appreciate your additional input.

     @isTest 
private class newDepartmentTest {
   
    @isTest static void testformDeptNow1(){
      
        List<Department__c> deptList = new List<Department__c>();
        for(Integer i = 0 ;i<10;i++)
        {
            // I am assuming that C1__c, C2__c, C3__c and C4__c are text fields, if not, fix it
            deptList.add(new Department__c(name='Wale'+i, level__c = 'level2 '+i, C1__c = 5, C2__c= 11, C3__c= 6, C4__c= 9)); 
        } 
        insert deptList;  

        Store__c[] sList = new Store__c[] {}; 
        for(Integer x=0; x<10; x++){
            Store__c ct = new Store__c (New_Description__c= 'desc' + x, Dpt__c = deptList[x].id );   
            sList.add(ct);
        }
        insert sList;
    
    
formDeptNow formDept = new formDeptNow();
    System.assertNotEquals(formDept.WrapBranchReportList1,null);
     //Department__c act = new Department__c();
      PageReference pageRef = Page.Room1; // Add your VF page Name here
            pageRef.getParameters().put('id', String.valueOf(deptList[0].Id));
            Test.setCurrentPage(pageRef);
      try{
        for(formDeptNow.WrapBranchReport1 x: formDept.WrapBranchReportList1)
        {
            x.isSelected1 = true;
        }
      } catch(Exception e) {
     System.debug('something went wrong, exception: ' + e);   
    } 
    System.assertNotEquals(formDept.WrapBranchReportList1.size(), null);
    
    formDept.processSelected1();
    //formDept.WrapBranchReportList1[0].isSelected1= true;
    System.assert(formDept.getbLs().size() > 0);
    
    System.assert(formDept.getdobjsuu().size() > 0);
    
    formDept.doSaveAndNew();
    
    formDept.Cancel1();
    
    formDept.Cancel2();
    
    formDept.Save1();
    
    formDept.step1();
    
    formDept.step2a();
      
}
}



User-added image
Steven NsubugaSteven Nsubuga
Hi Harvey, the problem was that we did not set a value for unit__c in the test class.
In the test below, I have set Unit__c = 'Kilo', change it to the right one. Code coverage will shoot upwards.
@isTest 
private class newDepartmentTest {
   
    @isTest static void testformDeptNow1(){
      
        List<Department__c> deptList = new List<Department__c>();
        for(Integer i = 0 ;i<10;i++)
        {
            // I am assuming that Unit__c, C1__c, C2__c, C3__c and C4__c are text fields, if not, fix it
            deptList.add(new Department__c(name='Wale'+i, level__c = 'level2 '+i, C1__c = 5, C2__c= 11, C3__c= 6, C4__c= 9, Unit__c = 'Kilo')); 
        } 
        insert deptList;  

        Store__c[] sList = new Store__c[] {}; 
        for(Integer x=0; x<10; x++){
            Store__c ct = new Store__c (New_Description__c= 'desc' + x, Dpt__c = deptList[x].id );   
            sList.add(ct);
        }
        insert sList;
    
    
formDeptNow formDept = new formDeptNow();
    System.assertNotEquals(formDept.WrapBranchReportList1,null);
     //Department__c act = new Department__c();
      PageReference pageRef = Page.Room1; // Add your VF page Name here
            pageRef.getParameters().put('id', String.valueOf(deptList[0].Id));
            Test.setCurrentPage(pageRef);
      try{
        for(formDeptNow.WrapBranchReport1 x: formDept.WrapBranchReportList1)
        {
            x.isSelected1 = true;
        }
      } catch(Exception e) {
     System.debug('something went wrong, exception: ' + e);   
    } 
    System.assertNotEquals(formDept.WrapBranchReportList1.size(), null);
    
    formDept.processSelected1();
    //formDept.WrapBranchReportList1[0].isSelected1= true;
    System.assert(formDept.getbLs().size() > 0);
    
    System.assert(formDept.getdobjsuu().size() > 0);
    
    formDept.doSaveAndNew();
    
    formDept.Cancel1();
    
    formDept.Cancel2();
    
    formDept.Save1();
    
    formDept.step1();
    
    formDept.step2a();
      
}
}


 
Harvey JethroHarvey Jethro
Thanks for the response. I really appreciate your time and effort. I'll try out the test code. Thanks a lot.