Is it worth it to try for 100% org coverage?

I saw an older post where someone had asked is it possible to get 100% code coverage, the responses were that it’s real easy to get around 80% and then to cover the other 20% you’re starting to get into edge cases and sometimes methods just cannot be tested.

I’ve been in orgs where there was 100% coverage, I’ve been in orgs where the coverage was in the high 80s, it didn’t seem to make a major difference in how the org ran or acted.

Is it just pride to get 100% coverage, is it worth the time to close the loop on the edge cases to inch up to 100%?

What is the best practice in how a developer should spend their time?

Answer

Yes, you should strive for 100%.

Actually, 100% is not a high enough bar. You should strive for 100% branch coverage. Do some reading on Cyclomatic Complexity to better understand.

Sometimes this type of coverage requires you to be more clever in how you design your code. One key strategy to achieve this goal is Separation Of Concerns.


Here is a simple example:

public static void complexOperation(List<SObject> records)
{
    for (SObject record : records)
    {
        if (someCondition)
        {
            // data transformation
        }
        else
        {
            // other transformation
        }
    }
    try
    {
        update records;
    }
    catch (Exception pokemon) // gotta catch em all!
    {
        // complex error handling
    }
}

Hmm, testing that is going to be quite difficult! SOC to the rescue.

public static List<SObject> filter1(List<SObject> records)
{
    List<SObject> filtered = new List<SObject>();
    for (SObject record : records)
        if (someCondition) filtered.add(record);
    return filtered;
}
public static List<SObject> filter2(List<SObject> records)
{
    List<SObject> filtered = new List<SObject>();
    for (SObject record : records)
        if (otherCondition) filtered.add(record);
    return filtered;
}
public static List<SObject> dataTransformation1(List<SObject> records)
{
    // data transformation
}
public static List<SObject> dataTransformation2(List<SObject> records)
{
    // other transformation
}
public static void safeUpdate(List<SObject> records)
{
    try
    {
        update records;
    }
    catch (DmlException dmx) // specificity yay!
    {
        // error handling
    }
}
public static void complexOperation(List<SObject> records)
{
    List<SObject> toUpdate = new List<SObject>();
    toUpdate.addAll(dataTransformation1(filter1(records));
    toUpdate.addAll(dataTransformation2(filter2(records));
    safeUpdate(toUpdate);
}

Every specific chunk of functionality above is much easier to test directly. Testing the composition of these can then be somewhat more cursory.

Attribution
Source : Link , Question Author : Dan Wooding , Answer Author : Adrian Larson

Leave a Comment