Apex Unit Testing

By in
460
Apex Unit Testing

Apex code written for every Salesforce customization needs to be unit tested by Apex Test classes and methods. In this article, we are going to go over some of the important things involved in Apex Testing.

 

Salesforce Test Class

A Test Class is used to test multiple test cases. Salesforce requires every test class to have at least 75% code coverage before it can be deployed to production.

 

Syntax:

@isTest

public class CustomTest {

// test methods

}

 

The test class should be annotated by @isTest annotation.

 

Salesforce Test Method

A test method is used for testing a specific test case. For multiple test cases, you need to create multiple test methods.

As a best practice, every functionality in Salesforce should have at least these 3 scenarios before deployment.

  1. Positive Test Case

This contains the test scenario for which the Apex class is written. It means a test that runs as expected.

  1. Negative Test Case

It is used to test the limits of the code. For example how the class reacts to exceptions/errors.

  1. Bulk test case

This is used to test the functionality with bulk records. A code may work for 1 record but this will test if it will work for multiple records.

 

Syntax:

@isTest public static void testMethod() {

 

//test data creation

//asserting if the functionality is working expected

}

 

Conclusion

Even though Salesforce says it needs 75%, we should try to cover the code 100%. Code coverage is not the main reason you should be writing test code. Your purpose is to test the functionality. As a result, you should follow all of the best practices mentioned.

Continue learning about Apex with some of my other posts, “Dynamic Apex” and “Ways to Deserialize Apex.”

 

Additional Resources

Cover Photo by Patrick Robert Doyle on Unsplash

Leave a reply

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