Write Unit Tests

Write Unit Tests for Apex in Salesforce

Comparte la información a tus amigos

Write unit tests for Apex is important to make sure the code is working and produces the expected results. In this article we will learn to write unit tests methods for Apex classes, triggers, controllers, flows and processes in Salesforce.

Considerations to Write Unit Tests

  • The test classes and methods must be annotated with @isTest statement and can be either private or public.
  • This methods should be static, return no values and no parameters.
  • Test data should be available to test functionality and data.
  • Can use @testSetup to set up test data in your class method.
  • The method being tested can be called directly from the test method.
  • To test triggers, include DML operations in test methods.
  • Test results can be verified with the System.assert() method.

Anatomy of an Apex Test Class

  • 1sth line: @isTest Indicates that this Apex class is a test class.
  • 4th line: @isSetup indicates that this method is used for creating test data.
  • 9th line: @isTest indicates that this method is a test method.
  • 10th line: The method should be static and void return, that means, it must not return any value. In addition, the method must not accept any arguments.
private class MyApexClassTest {
  private static void setupTestData() {
    //Create data to use in the test methods.

  private static void myTestMethod() {
    //Test code here.


Structure of Write Unit Tests

  • Prepare valid Data for test.
  • Execute the methods to be tested.
  • Verify Results using assertions and make adjustments if it’s needed.

All unit tests follow the same structure to create test data. In addition, the data is not commited so it does not need to be deleted.

Best Practices When Write Unit Tests

  • Make multiple test cases. For example, consider positive, negative and user-restricted code behavior.
  • Unit tests should create their own test data to not depend on existing data in the org.
  • No need to delete data because unit tests do not commit changes.
  • Always verify results using System.assert().
  • When the expected result does not match the actual by System.assert() an exception is thrown.
  • Should test only one aspect of code at a time to make it easier to understand the purpose.
  • Add your test to a test suite when a new bug is found to simplify regression testing.
  • Test-driven development or creating unit tests before writing new code can help to understand how code will be used.

Code Coverage Computation

  • Code coverage Percentage formula: CCP = (number of covered lines) / (number of covered lines + number of uncovered lines)
  • Not counted and does not impact code coverage percentage: Comments, class name definition, lines that only contain brackets and System.debug statements.

Sample of Test for an Apex Trigger

//Trigger Class
trigger ContactTrigger on Contact (before insert) {
  List <String> phoneNumbers = new List <String>();
  List <Account> accountList = new List <Account>();
  Map <String, Account> mapAccounts = new Map <String, Account>();

  if (Trigger.isBefore &amp;&amp; Trigger.isInsert) {
    for (Contact c : Trigger.New) { phoneNumbers.add(c.PhoneNumber); }
    accountList = [SELECT Id, MobilePhone FROM Account WHERE MobilePhone IN :phoneNumbers];
    for (Account a : accountList) { mapAccounts.put(a.MobilePhone, a); }
    if (mapAccounts.size() != 0) {
      for (Contact c : Trigger.New) {
        if (mapAccounts.containsKey(c.PhoneNumber)) {
          c.AccountId = mapAccounts.get(c.PhoneNumber);
//Test Class
private class ContactTriggerTest {

  static void createTestData() {
    Account a = new Account(Name='Test Account', MobilePhone = '1234');
    insert a;

  static void testMapping() {
    Contact cont = new Contact(LastName = 'Vallejos', PhoneNumber = '1234');
    insert cont;

    Account acc = [SELECT Id, Name FROM Account WHERE Name = 'Test Account' LIMIT 1];
    Contact cont2 = [SELECT Id, AccountId FROM Contact WHERE Id = :cont.Id];

    System.AssertEquals(acc.Id, cont2.AccountId);

More Information

For more information about Salesforce can go to Ways to include Visualforce pages into Lightning Platform

Comparte la información a tus amigos


  1. Every weekend i used to pay a quick visit this site, because i want enjoyment, since this this website conations
    in fact nice funny information too.

    My webpage: click here (Kelsey)

  2. buy cialis online from india This method produces estimates of the 24 hour rhythm adjusted time series mean, or MESOR midline estimating statistic of rhythm; an average value of the rhythmic function fitted to the data, as well as the amplitude one half the extent of change explainable by rhythmicity and acrophase crest time expressed as a lag in time from a designated reference; here, the time of awakening from nocturnal sleep for every fitted component of a given period; for this study, 24 and 12 hours