I have written a test class for a class and its coverage is above 75% but I want to increase it and found that a particular for loop is not being covered(written Between ** below). Please help me with this. I don't have the idea how to test for the for a loop.

myContactList= Database.query(queryString);
            for(Contact c : myContactList){
                **RecData recordsData = new RecData ();
                RecData.value= String.valueOf(c.get('id'));
                RecData.label = String.valueOf(c.get(filterField));
                RecData.cont = c;
        } catch (Exception err) {}
        return recDataList;

Here the the RecData is the inner wrapper class with three properties which are covered in test class.


To make this code more testable, you need to extract the loop body to a separate code unit. In your case there are 2 options:

  1. RecData constructor
  2. Just a separate method

Then just write tests for that extracted unit. That would do the thing.


The point of tests is to confirm that the code does what the requirements specified so start with that mindset when writing tests. Code coverage is just a crude indicator.

The data already in your org is (except for some special cases) not visible to your test. So your test will need to insert data that causes your queryString query to return rows so that the loop executes.

Also 99% of the time this } catch (Exception err) {} is a bad idea; normally better to let the exception bubble up so you know something has gone wrong.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.