Apex Unit Tests

Apex code can only be written in a sandbox environment or a Developer org, not in production. Apex code can be deployed to a production org from a sandbox. Also, app developers can distribute Apex code to customers from their Developer orgs by uploading packages to the Force.com​ AppExchange. In addition to being critical for quality assurance, Apex unit tests are also requirements for deploying and distributing Apex. The following are the benefits of Apex unit tests.

Code Coverage Requirement for Deployment

Before you can deploy your code or package it for the Force.com​ AppExchange, at least 75% of Apex code must be covered by tests, and all those tests must pass. In addition, each trigger must have some coverage. Even though code coverage is a requirement for deployment, don’t write tests only to meet this requirement. Make sure to test the common use cases in your app, including positive and negative test cases, and bulk and single-record processing.

Test Method Syntax

Test methods take no arguments and have the following syntax:

@isTest static void testName() { 
		// code_block
}

The visibility of a test method doesn’t matter, so declaring a test method as public or private doesn’t make a difference as the testing framework is always able to access test methods. For this reason, the access modifiers are omitted in the syntax.

Test methods must be defined in test classes, which are classes annotated with isTest. This sample class shows a definition of a test class with one test method.

@isTest
private class MyTestClass {
    @isTest static void myTest() {
        // code_block
    }
}

Test classes can be either private or public. If you’re using a test class for unit testing only, declare it as private. Public test classes are typically used for test data factory classes, which are covered later.

Code Coverage & Running Test Suites

Info on code coverage and test suites here.