Free Salesforce Developers Tutorials >

Chapter 11 - Apex Testing >

Unit Testing in Apex

Unit Testing in Apex

What You’ll Learn

S2 Labs

What Are Unit Testing In Apex & How To Write Them?

Unit tests are class methods that verify whether a particular piece of code is working properly or not.

Unit test methods take no arguments, commit no data to the database, send no emails, and are flagged with the testMethod keyword or the isTest annotation in the method definition. 

Also, test methods must be defined in test classes, that is, classes annotated with isTest.

Create different test methods to test different functionalities.

In each test, method writes different test cases to test your code whether it is working properly with the different inputs or not.
After API version 32 test method is used as @istest.


Private class myClass {
  Static void testMethod myTest {
     // code block
Private class myClass {
  static void myTest() {
    // code block

Use the isTest notation to define classes and methods that only contain code used for testing your application. The isTest annotation on methods is equivalent to the testMethod keyword.


Classes defined with the isTest annotation don’t count against your organization limit of 3 MB for all Apex code.

This is an example of a test class that contains two test methods:

Private class MyTestClass {
      // Methods for testing
  static void test1() {
      // Implement test code
  @isTest static void test2() {
       // Implement test code

  • Classes and methods defined as isTest can be either private or public. The access level of the test methods doesn’t matter. This means you don’t need to add an access modifier when defining a test class or test methods. The default access level in Apex is private. The testing framework can always find the test methods and execute them, regardless of their access level.
  • Classes defined as isTest must be top-level classes and can’t be interfaces or enums.
  • Methods of a test class can only be called from a running test, that is, a test method or code invoked by a test method, and can’t be called by a non-test request.


Characteristics Of Unit Testing Methods

Some characteristics of unit test methods are that:

  • are contained in separate classes which are called Test Classes specifically created to run tests.
  • do not commit any data to the database.
  • do not send any emails.
  • are always flagged with the keyword testMethod or @isTest annotation at the method definition level.
  • must always be defined in a test class. This test class should be annotated with @isTest annotation.
  • are always defined as static methods.

Unit Testing Considerations

Here are some things to note about unit tests.

  • Test methods can’t be used to test Web service callouts. Instead, use mock callouts such as Test Web service callouts and Testing Http Callouts.
  • You can’t send email messages from test methods.
  • Since test methods don’t commit data created in a test, you don’t have to delete test data upon completion.

Accessing Private Test Class Members:

If class Members are private, they aren’t visible to the test class.

  1. Call the private method in the public method which is already exposed to the test class.
  2. Annotated with these class members with @testvisible which allows them to be accessed by test methods and only code running in the test context.

For Example:

 public class VisibleSampleClass {
    // Private member variables 
    @TestVisible private integer recordNumber = 0;
    @TestVisible private string areaCode = ‘(415)’;
    // public member Variable 
    public integer maxRecords = 1000;
    // Private inner class 
    @TestVisible class Employee {
        String fullName;
        String phone;
        // Constructor 
        fullName = s;
        Phone = ph;
        @TestVisible Employee(String s, String ph) {}
    // Private method 
    @TestVisible private string privateMethod(Employee e) {
        System.debug(‘I am private’);
        String phone = areCode + ‘’ +e.Phone;
        String s = e.fullName + ‘\’s phone number is’ + phone;
        return s;
    // Public method 
    public void public method() {
        System.debug(‘I am public’);
    // Private custom exception class 
    @TestVisible private class MyException extends Exception {}


Test methods aren’t allowed in non-test classes, you must move the test methods from the old class into a new test class (a class annotated with isTest) when you upgrade the api version of your class. 

You might run into visibility issues when accessing private methods or member variables of the original class.

 In this case, just annotate these private members with TestVisible.

Unit Testing Best Practices

Cover as many lines of Apex code as possible, including all the branches of conditional logic.

  • Use the System.runAs method to test record-level access for users in the code being tested.
  • Always handle all exceptions that are caught, instead of merely catching the exception.
  • Make use of the system. assert and system.assertEquals statements in your Test Classes and methods to verify expected results.
  • Try to cover both positive and negative test scenarios by passing valid and invalid inputs to the Apex code.
  • Use startTest and stopTest methods to avoid Governor Limits while testing the actual code of functionality. All test data should be created outside and prior to calling these methods.

Download Study Material

Get access to exclusive study material for Salesforce Certification and ace your exams!

Download Now

Our Salesforce Certification Courses

Hey there! Glad you made it through our Salesforce Developer Training for beginners . But wait! We've got some high-in-demand Salesforce courses for you to take your Salesforce skills to the next level, making you a desired professional in the Salesforce job market.

Post a Comment

Your email address will not be published. Required fields are marked *