Quick Reference Study Notes for Salesforce Apex Unit Testing (Foundation)

Salesforce Apex Unit Testing

Salesforce provides a testing framework which enables to write and execute tests for the Apex classes and triggers. This framework makes it easy to test Apex code. Below are the benefits of Apex unit tests.

  • Ensuring that Apex classes and triggers work as expected

  • Having a suite of regression tests that can be rerun every time classes and triggers are updated to ensure that future updates  make to app don’t break existing functionality

  • Code coverage requirements fulfil for deploying Apex to production or distributing Apex to customers via packages

  • High-quality apps delivered to the production org.

  • High-quality apps delivered to package subscribers, which increase customers trust


 

Test Method Syntax

Test methods do not take  arguments and have the following syntax:

 

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


 

Alternatively, syntax is:

 

static testMethod void testName() {
   // code_block
}


 

Using isTest annotation instead of the testMethod keyword is more flexible.

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 not specified in the syntax.

Test methods must be defined in test classes, and these classes are annotated with ”isTest”. Below 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 test class used for unit testing only, declare it as private. Public test classes are used for test data factory classes, which are covered later.

Example:

The following example of a test class with a test method. The class method that’s being tested takes a number as an input. It adds the number and returns the sum as a result. Let’s start with add the custom class and its test class.

  1. In the Developer Console, click File | New | Apex Class, and enter Calculation for the class name, and then click OK.

  2. Replace the default class body with the following.

  3.  

public class Calculation {

// Take a  numbers as a parameters and returns the sum.

public static Decimal addition(decimal param1, decimal param2) {

   Decimal total = param1 + param2;

  return total.setScale(2);

       }

}


 

Press Ctrl+S to save your class.

Repeat the previous steps to create the CalculationTest class. Add the following for this class.

@isTest

private class CalculationTest {

@isTest static void testAddNumbers() {

    Decimal sum = Calculation.addition(10, 20);

   

    // Simulate Without comments

    System.assertEquals(30, sum);

 

    // Simulate With comments

    System.assertEquals(30, sum,'Sum of numbers is not expected.');

    

}

}


 

The CalculationTest test class verifies that the method works as expected by calling it with different inputs.

The System.assertEquals() method is calling for logic verification, which takes two parameters: the first is the expected value, and the second is the actual value. Another type of this method that takes a third parameter—a string that describes the comparison being done. This string is logged if the assertion fails.

Let’s run the methods in this class.

  1. In the Developer Console, click on Test | New Run.

  2. Under Test Classes, click CalculationTest .

  3. To add all the test methods in the CalculationTest class to the test run, click Add Selected.

  4. Click Run.

  5. In the Tests tab, See the status of tests as they’re running. Expand the test run, and expand again until you will see the list of individual tests that were run. They all have green check marks means test cases passed successfully.

  6. After running the tests, code coverage is automatically generated for the Apex classes and triggers in the Org. You can check the code coverage percentage in the overall code coverage tab of the Developer Console. In this example, the class you have tested, the Calculation class, has 100% coverage.


 

Whenever apex code is modified, rerun the tests to refresh code coverage results.

But there is a known issue with the Developer Console prevents it from updating code coverage correctly when running a subset of tests. To update code coverage results, use Test | Run All rather than Test | New Run.

Assertion fails: For example, let’s modify the parameter test and pass in a false expected value for the sum. This causes the corresponding test method to fail.

  1. Change the testAddNumbers() test method to the following.

  2.  

 @isTest static void testAddNumbers() {
       Decimal sum = Calculation.addition(10, 20);     
       // Simulate failure
       System.assertEquals(0, sum, 'Total  is not expected.');
   }

 

  1. To execute the previous test, click the latest run in the Tests tab, and then click Test | Rerun.

  2. The assertion in testAddNumbers() fails and throws a fatal error (an AssertException that can’t be caught).

  3. Check the results in the Tests tab by expanding the test. The test run reports one test is failed. To get more details about the failure, double-click on the test run.

  4. Detailed results appear in a separate tab as shown in the below image.


     

  5. To get the error message, double-click inside the Errors column for the failed test.

  6. You will see the following. The descriptive text next to Assertion Failed: is the text that we provided in the System.assertEquals() statement.

  7. System.AssertException: Assertion Failed: Total  is not expected.: Expected: 0, Actual: 30.00.

 

Code Coverage

Before deploying your code or package it for the Lightning Platform​ 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 with this we must confirm the logic is correct or not.

Do not aim for 75% coverage, which is the lowest coverage that the Lightning Platform requires for deployments and packages. The more test cases that tests cover, the higher the likelihood that code is robust. Sometimes, even after write test methods for all class methods, code coverage is not at 100%. The common cause is not covering all data values for conditional code execution.

 

Let’s run this test class (CalculationTest) in the Developer Console and check code coverage for the corresponding Calculation class that this test covers. After the test run finishes, the code coverage for Calculation is shown as 100%. If you open this class in the Developer Console, you see three blue (covered) lines, as shown in this image. If lines covered with red then those are uncovered lines.

Create and Execute a Test Suite

A test suite is a collection of Apex test classes that run together. For example, create a suite of tests that run every time when we prepare for deployment or Salesforce releases a new version. Set up a test suite in the Developer Console to define a set of test classes that execute together regularly.

Suppose, You have two test classes in your Org.These two classes are not related to each other, but for the moment assumed that they are and there are situations when you want to run these two test classes but do not want to run all the tests. Then create a test suite that contains both classes, and then execute the tests in the suite.

  1. Go to Developer Console, click on Test | New Suite.

  2. Enter CalculationTestfor the suite name, and then click OK.

  3. Select CalculationTest.

  4. Add the selected test classes to the suite and click >.

  5. Click Save.

Creating Test Data

Salesforce records that are created in the test methods are not committed to the database. They are rolled back when the test case execution finishes. This rollback behaviour is useful for testing because you don’t have to clean up your test data after the test executes.

By default, Apex tests do not have access to pre-existing data in the org, except for access to setup and metadata objects, such as the User or Profile objects. Set up test data for your tests. Creating test data makes tests more robust and prevents failures that are caused by missing or changed data in the Org.

To access org data, annotate the test method with @isTest(SeeAllData=true). This is not best practice to do so, there are times when a test method needs access to pre-existing data.

*NOTE : "This study material is collected from multiple sources to make a quick refresh course available to students."

This website uses cookies to improve user experience. By using our website you consent to all cookies in accordance with our Cookie Policy. More info. I Agree