Apex Test Class Best Practices

Once an Apex class is written, it must pass through a unit test, which verifies whether a particular piece of code or function is working properly or not, before it is deployed. Also, at least 75% of our apex code must be covered in order to successfully deploy the code to the production organization. Unit tests are written in Apex Code and annotated with the test Method keyword.

What is a Test Method?

Once an Apex class is written, it must pass through a unit test, which verifies whether a particular piece of code or function is working properly or not, before it is deployed. Also, at least 75% of our apex code must be covered in order to successfully deploy the code to the production organization. Unit tests are written in Apex Code and annotated with the testMethod keyword.

E.g.: Static testMethod void methodname()

Use of @isTest annotation
This annotation defines a class as a test class that contains code for testing our application and these classes are not counted against our organization limit of apex code. Classes annotated with @isTest can be declared as private or public.

E.g.:

@isTest
Private class ExampleTest
{
    Static testmethod void test1()
    {
        // Your code
    }
}    

Use of @TestVisible annotation
It allows to access private or protected members (methods, variables, and inner classes) and of another class outside the current test class. Here, we don’t need to compromise with access modifiers for the sake of code coverage. We just need to append @TestVisible notation before any private or protected member of a class.

E.g.:

Public class TestVisibleExample 
{
@TestVisible private static Integer recordNumber = 1;
@TestVisible private static void updateRecord(String name) 
{}
}   

Use of IsTest(SeeAllData=true) Annotation
This annotation grants access to all data in the organization, and it is available for Apex code saved using Salesforce API version 24.0 and later, but as a best practice, it is recommended not to use this annotation unless there is a unique need.

E.g.: PriceBook creation (sObjects that doesn’t allow DML operation), so, here, we can use this annotation to get pre-existing data stored in the organization.

Use of System.runAs() method
Normally, all Apex codes run in System mode, and therefore the current user’s various permissions and record sharing rules are not taken into consideration. The system method, System.runAs(),lets us write test methods that change user contexts to either an existing user or a new user. All of that user’s record sharing is then enforced. You can only use runAs in a test method. But runAs() does not validate CRUD or Field Level Security permissions.

Use of Test.isRunningTest() method
There may be some cases where we cannot test a piece of code in normal manner. In those cases, use Test.isRunningTest() in your code to identify that context of class is Test or not.

E.g.: We can generate fake response easily, while testing web services.

Use of System.Assert/System.AssertEquals Methods
These methods are used to ensure that the Apex code executes and returns the expected value.
System.Assert: It accepts two parameter: First one (mandatory) is the condition to test and the second one is used to display a message in case the condition fails.
Syntax: System.assert(var1 == var2,”msg”)
System.AssertEquals: It accepts three parameters; the first two (mandatory) are the variables that will be tested for equality or inequality, and the third (optional) one is used to display a message in case the condition fails. Syntax: System.assertEquals(var1, var2,”msg”);

Use of Test.startTest/Test.stopTest method
Test.startTest and Test.stopTest, are used when testing governor limits. When you call Test.startTest method, you will get a fresh set of governor limits for the remainder of the test until you call Test.stopTest, and each test method is allowed to call this method only once.

Test methods will no longer be able to compile in a non-test class
Now starting with the Summer ’13 release, you will not able to compile test method in the same class as your regular executable code. Apex test method need to be created in a separate class (A “test class” is one marked with the @isTest annotation), and these changes will be applicable for new classes written in v28.0 and above.

Avoid Hardcoding IDs
Never hard code ids of any sObjects inside test method, but if a Constant needs to be asserted, then make use of Constant class or Custom Labels or Custom Settings because hard coding strings in unit tests may result in test failure when things like Pick list values change.

Summary
Following Apex test class best practices is vital to ensure the quality of the code and also it simplifies the regression testing.

About MST

At MST Solutions our cornerstone is to adapt, engage and create solutions which guarantee the success of our clients. The talent of our team and experiences in varied business verticals gives us an advantage over other competitors.

Recent Articles

Work with us.

Our people aren’t just employees, they are key to the success of our business. We recognize the strengths of each individual and allow them time and resources to further develop those skills, crafting a culture of leaders who are passionate about where they are going within our organization.