How to increase code coverage quickly in Salesforce


One of the requirements from Salesforce to deploy Apex code to the production environment or upload package to the Salesforce AppExchange related with Ape[ code coverage. Unit tests must cover at least 75% of your Apex code, and those tests must pass.

Code coverage indicates how many executable lines of code in your classes and triggers have been exercised by test methods.

Code coverage serves as one indication of test effectiveness but doesn’t guarantee test effectiveness. The quality of the tests also matters, but you can use code coverage as a tool to assess whether you need to add more tests. While you need to meet minimum code coverage requirements for deploying or packaging your Apex code, code coverage shouldn’t be the only goal of your tests. Tests should assert your app’s behavior and ensure the quality of your code.

Disclaimer: following method is not a best practice but it can make sense if you need to increase the code coverage to several percent quickly for urgent deploy to production.

Solution

You need to create Apex Class with a lot of lines of the code, like following:

public class FakeClassForCoverage {

    static void justIncrement() {
        Integer i = 0;
        i++;
        i++;
        i++;
        ...
        i++;
        i++;
    }

    static testmethod void testIncrement() {
        justIncrement();
    }

and simple unit test to cover this lines.

The additional percentage will depend on the number of lines in Apex Classes that you already had in Salesforce and the number of lines in new FakeClassForCoverage class. Than you had fewer lines of the code in you Org and FakeClassForCoverage class have more lines so additional percentage will be more.

You need to implement Unit Tests not only for the coverage but for checking the logic in your code. It really needs to use Asserts to check the states and the data.

We suggest using this method only if you need to perform urgent hotfix deployment to the production environment and you facing with Code Coverage issue.

If you have any questions or problems related to Salesforce Development – let us know. We always glad to help you.