Skip to main content

Salesforce

Building Quality in Salesforce: Exploring the Apex Testing Framework

Coding See Through

Apex Unit Test: Why do we need to write test classes in Salesforce?

In Salesforce, writing test classes is an essential practice for ensuring the quality and reliability of your code. They are specifically used to test the functionality of your Apex classes, triggers, and other components.

Test Classes or a Test Method verify whether a particular piece of the code is working the way you expect it. If that particular piece of code fails, then the developers or the testers can accurately locate the test class which is failing, and they can figure out which code is not working as expected.

So test classes are very helpful in order to test your changes in order to see if the code is working as expected or not. and it is easy to debug the error as well.

How to identify if an Apex class is a test class?

In Salesforce Apex, test classes are used to write unit tests for your Apex code. These test classes are identified by the @isTest annotation. Here’s how you can identify if a class is a test class in Salesforce Apex:

  1. Open the class file you want to identify as a test class.
  2. Look for the @isTest annotation at the class level. Test classes in Salesforce Apex are annotated  @isTest to indicate that they contain test methods.

How can we write test classes in Apex Salesforce?

To write test classes in Apex Salesforce, you can follow these steps:

  1. Create a Test Class: Create a new Apex class specifically for testing your target Apex class. The test class should have the @isTest annotation at the class level to indicate that it is a test class.
    @isTest
    public class MyApexClassTest {
        // Test methods added here
    }
    

     

  2. Write Test Methods: Inside the test class, create test methods to cover different scenarios and test cases for your target Apex class. Each test method should have the @isTest annotation as well.
    @isTest
    public class MyApexClassTest {
        @isTest
        public static void testMethod1() {
            // Test logic goes here
        }
    
        @isTest
        public static void testMethod2() {
            // Test logic goes here
        }
    
        // Add more test methods as needed
    }
    
  3. Prepare Test Data: Before executing the test methods, create the necessary test data that simulate the conditions you want to test. This includes creating test records, setting up required fields, and populating related objects.
    @isTest
    public class MyApexClassTest {
        @isTest
        public static void testMethod1() {
            // Prepare test data
             Acct testAcct = new Acct(Name = 'Test Acct'); 
             insert testAcct; 
    
            // Test logic goes here
        }
    
        // Add more test methods with data preparation
    }
    

     

  4. Invoke the Target Class: In each test method, instantiate the target Apex class and invoke its methods to test the desired functionality. Pass the test data you prepared as input parameters to the target class methods.
    @isTest
    public class MyApexClassTest {
        @isTest
        public static void testMethod1() {
            // Prepare test data
            Acct testAcct = new Acct(Name = 'Test Acct');
            insert testAcct;
    
            // Invoke the target class
            MyApexClass myClass = new MyApexClass();
            myClass.myMethod(testAccount.Id);
    
            // Assertions and validation go here
        }
    
        // Add more test methods invoking the target class
    }
    
  5. Perform Assertions: After invoking the target class methods, perform assertions to verify the expected behavior of your code. Use system assertions or custom assertions to validate that the actual results match the expected results.
    @isTest
    public class MyApexClassTest {
        @isTest
        public static void testMethod1() {
            // Prepare test data
            Acct testAcct = new Acct(Name = 'Test Acct');
            insert testAcct;
    
            // Invoke the target class
            MyApexClass myClass = new MyApexClass();
            myClass.myMethod(testAccount.Id);
    
            // Perform assertions
            System. assertEquals('Expected Value', myClass.SomeField);
    
            // Add more assertions as needed
        }
    
        // Add more test methods with assertions
    }
    

     

  6. Run the Tests: Save the test class and run it either from the Salesforce Developer Console or by using the Salesforce CLI. The test results will indicate whether the tests passed or failed and provide information on code coverage and the exact location of failed and passed test classes.

Some of the Best Practices for Apex Testing and Code Coverage

  1. Test Coverage: Salesforce enforces a minimum code coverage requirement of 75% for both Apex classes and triggers. but try to achieve the highest code coverage possible, do not just aim for 75% coverage because that is the minimum requirement in order to deploy the code to production.
  2. Test Isolation: the Test.startTest() and Test.stopTest() methods are used to delineate the boundaries of a specific test execution context. One common best practice is to create all the necessary test data before calling Test.startTest()
  3. Utilize Assertions: Use assertions within your test methods to verify that the actual results match the expected results. Leverage assertion methods such as System.assertEquals(), System.assertNotEquals(), System.assert(), and others to validate the behavior of your code.
  4. Regularly Monitor Code Coverage: Continuously monitor your code coverage to catch any regressions or decreases in coverage. Use tools like the Developer Console, Salesforce CLI, or CI/CD integrations to automate code coverage checks and alerts.

Note:

We can move the code from one sandbox to another if we do not have 75% code coverage, we still can move our code from that one particular sandbox to another sandbox. That is fine without having an issue but if you want to move your code from your sandbox to the production environment, then you need a minimum of 75% good code coverage in order to deploy the code to production.

Conclusion:

By following these best practices and leveraging the features of the Apex Testing Framework, you can ensure the quality and reliability of your Salesforce applications. Effective unit testing helps catch bugs early, validate expected behavior, and build a solid foundation for development and maintenance.

References:

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_testing.htm

https://trailhead.salesforce.com/content/learn/modules/apex_testing/apex_testing_intro

 

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Anshuli Nikhare

Anshuli Nikhare is a Salesforce Developer. She has over 2 years of IT industry experience working as an Associate Technical Consultant at Perficient based out of Nagpur. She is a Certified Salesforce Platform Developer (PD1). Anshuli enjoys how being a Salesforce Developer helps her skillset explore. She is a skilled researcher who can identify opportunities in a given arena, is a supportive teammate, and is an employee willing to go the extra mile to help others.

More from this Author

Follow Us
TwitterLinkedinFacebookYoutubeInstagram