+ Start a Discussion
Iqbal HossainIqbal Hossain 

For loop and nested IF code coverage

Hi, I could not Apex test coverage to 100%. At loop nested IF was uncovered. The total coverage is 92%.

Apex Class:
 
public class Income{
    private String employeeSortOrder;
    public String currentUserId{get;set;}
    public User currentUser{get;set;}
    
    public Income() {
        currentUserId =  UserInfo.getUserId();
        currentUser = Database.query('SELECT id, Name, EmployeeNumber From User Where id=:currentUserId');
        this.employeeSortOrder = 'Name ASC';  
    }
    
    public List<Employee__c> getEmployees(){
       List<Employee__c> employees = Database.query(
           'SELECT Name, Alias__c, EmployeeCode__c, Department__c, Status__c ' +
            'FROM Employee__c ' +
            'ORDER BY ' + employeeSortOrder);
       
       for (Integer i = 0; i< employees.size(); i++){
           //Next 2 lines was not covered!
           if(currentUser.EmployeeNumber==employees[i].EmployeeCode__c) {
               employees.remove(i);
           }
        }     
            
       return employees;
    }
    
    //Sort by employee code
    public void sortByEmployeeCode() {
        if(employeeSortOrder == 'EmployeeCode__c ASC') {
            this.employeeSortOrder = 'EmployeeCode__c DESC';
        }
        else {
            this.employeeSortOrder = 'EmployeeCode__c ASC';
        }
       
    }
    
    //Sort by department
    public void sortByEmployeeDepartment() {
        if(employeeSortOrder == 'Department__c ASC') {
            this.employeeSortOrder = 'Department__c DESC';
        }
        else {
            this.employeeSortOrder = 'Department__c ASC';
        }
    }
    
    //Sort by status
    public void sortByEmployeeStatus() {
        if(employeeSortOrder == 'Status__c ASC') {
            this.employeeSortOrder = 'Status__c DESC';
        }
        else {
            this.employeeSortOrder = 'Status__c ASC';
        }
    }  
}

Test Class:
@isTest
public class incom_test{

    static testmethod void incom_test(){
        Income i = new Income();
        String result = i.currentUserId;
        User resultUser = i.currentUser;
          
        i.sortByEmployeeCode(); //Ascending
        i.sortByEmployeeCode(); //Descending       
        i.sortByEmployeeDepartment(); //Ascending
        i.sortByEmployeeDepartment(); //Descending
        i.sortByEmployeeStatus(); //Ascending
        i.sortByEmployeeStatus(); //Descending
    }
    
    static testmethod void incom_get_employee_test(){
        Income i = new Income();
        User u = i.currentUser;
        u.EmployeeNumber = '003';
        List<Employee__c> e = i.getEmployees();
        System.assertEquals(9,e.size());      
    }

}



Please help me how can I complete it to 100%?
Best Answer chosen by Iqbal Hossain
Martijn SchwarzerMartijn Schwarzer
Hi Iqbal,

You are not creating test data in your test class. By default, test methods do not see any data in the org, so you will have to create your own.

Just insert an Employee__c record that contains the necessary values and you will see your testcoverage go to 100%.

Also, please take a look at the Apex Testing Best Practices for more information:

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_testing_best_practices.htm

Hope this helps!
Happy coding!

Regards,
Martijn Schwärzer

All Answers

Martijn SchwarzerMartijn Schwarzer
Hi Iqbal,

You are not creating test data in your test class. By default, test methods do not see any data in the org, so you will have to create your own.

Just insert an Employee__c record that contains the necessary values and you will see your testcoverage go to 100%.

Also, please take a look at the Apex Testing Best Practices for more information:

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_testing_best_practices.htm

Hope this helps!
Happy coding!

Regards,
Martijn Schwärzer
This was selected as the best answer
claperclaper

Try this: 

@isTest
public class incom_test{
    
   @testSetup static void setup() {

        Profile p1 = [SELECT Id FROM Profile WHERE Name = 'System Administrator'];

        User[] userList = new User[]{};
        User u = new User();

        u.FirstName = 'Test';
        u.LastName = 'Admin';
        u.EmployeeCode = '003';
        u.Email = 'test@admin.com';
        u.Username = 'test@adminUnique.com';
        u.Alias = 'astest';
        u.ProfileId = p1.Id;
        u.TimeZoneSidKey    = 'America/Denver';
        u.LocaleSidKey      = 'en_US';
        u.EmailEncodingKey  = 'UTF-8';
        u.LanguageLocaleKey = 'en_US';
        userList.add(u);

        system.debug('u contains ' + u);

        insert userList; 

        system.runas(u){
        // Create common test Employee__c records
        List<employee__c> employeeList = new List<employee__c>();
        for(Integer i=0;i<10;i++) {
            employeeList.add(new Employee__c(Name = 'Employee '+i,
                                                                        EmployeeCode__c = i,
                                                                        Deparment__c = 'dummy dept',
                                                                        Status__c = 'active',
                                                                        Alias__c = 'Emp'+1+'alias'
                                                                       )
                                         );
        }
        insert employeeList;   
       }
    }


    static testmethod void incom_test(){
        user u = [Select id from user where username = 'test@adminUnique.com'];
        system.runas(u){
        Income i = new Income();
        String result = i.currentUserId;
        User resultUser = i.currentUser;
          
        i.sortByEmployeeCode(); //Ascending
        i.sortByEmployeeCode(); //Descending       
        i.sortByEmployeeDepartment(); //Ascending
        i.sortByEmployeeDepartment(); //Descending
        i.sortByEmployeeStatus(); //Ascending
        i.sortByEmployeeStatus(); //Descending
        }
    }
    
    static testmethod void incom_get_employee_test(){
        user u = [Select id from user where username = 'test@adminUnique.com'];
        system.runas(u){
        Income i = new Income();
        User u = i.currentUser;
        u.EmployeeNumber = '003';
        update u;

        

        List<Employee__c> e = i.getEmployees();
        System.assertEquals(9,e.size());      
        }
    }

}

always remember to crear you own data set for testing. Great job including assertion statements! I would also recomend using the test.startTest() and test.StopTest() methods too.