Tuesday, May 10, 2011

Avoid single-line Salesforce Apex if expressions for code coverage

In Salesforce Apex a single line if expression should be avoided if you want to ensure full code coverage by the automated tests.

I found that Apex code would show as having full test coverage even if the expression never evaluated to true. For example, the following would show as being completely tested even though the doSomething method was never called.

Boolean exampleCondition = false;
if (exampleCondition) { doSomething(); }


  1. Like most code coverage libraries on other platforms (including EMMA and Clover), reporting is done by line. The condition is being evaluated in your example, so something is being done on that line.

  2. It appears Salesforce is tracking line coverage rather than statement or branch coverage of Apex code.

    It's not an issue in itself, but something to be aware of that the layout and formatting of code can affect code coverage results.

    We usually avoid single line conditionals from a Apex code standards perspective to avoid this issue.