As all Salesforce developers that have ever written any APEX code know: The code requires test coverage to become eligible for deployment to a production org. To deploy to a production system, 75% test coverage is required. There's a funny thing with the calculation of this coverage though.

Contrary to what one might expect, the calculation of coverage does not actually look at the number of code statements (a statement ends with a ;) you cover with unit tests. What's actually being calculated is the number of lines (a line ends with a line feed) you have covered. As a consequence, one could theoretically write an entire class on 1 line and then only need to cover the first statement of this line, to get to 100% coverage.

Below is an example to illustrate this. First screenshot shows a class that has some arbitrary code, all on 1 line.

You should recognize that the first if-branche of this code, will actually never be executed. Still, the code can be covered to 100%, as you can see by the full code being highlighted blue, after running the test on the screenshot below.

Now, let's execute the same test, but not before modifying the class code first. Let's spread the statements across more than 1 line. As you can see by the color coding on the screenshot below, the class all of the sudden does not reach 100% anymore, despite running the same test code! Only 80% this time.

This blog should by no means be interpreted as an encouragement to cheat around with test code, let alone putting entire classes on one line. Just to give you some insight in the inner workings of test coverage in Salesforce...

 

Add comment


Security code
Refresh