In this blog, we will study test classes in apex, the best practices of test classes, and how to implement them. So, let’s begin with an introduction.
- The apex testing framework allows us to write and execute tests for the apex classes and triggers on the lightning Platform.
- Apex unit tests ensure high quality for our apex code and let us meet requirements for deploying apex.
- Apex code is only written in a sandbox environment or a developer org, not inside a production org.
- Apex code can be deployed to a production org from a sandbox. App developers can also distribute apex code to customers from their developer orgs by uploading packages to the lightning platform AppExchange.
- In addition to being critical for quality assurance, Apex unit tests are also requirements for deploying and distributing the Apex code.
Advantages of Apex Unit Testing
- It ensures that our apex classes and triggers are working properly.
- Having a suite of regression tests that can rerun every time classes and triggers are updated to ensure that future updates, we make to our app don’t break existing functionality.
- It meets the code coverage requirements for deploying apex to production or disturbing apex to customers vis packages.
- It ensures the delivery of high-quality apps on the production org, which makes production users more productive.
- It also ensures that high-quality apps are delivered to package subscribers, which increases the customer’s trust.
Code Coverage Mandate for Deployment
- Before deploying the code or packaging it for the lightning Platform AppExchange, at least 75% of Apex code must be covered by tests, and all those tests must pass.
- Each and every trigger must have some coverage.
- Always make sure to test the common use cases in your app, including the positive and negative test cases, and bulk and single-record processing.
- We can implement two or three methods in the apex test class to test a method in the apex code.
Points to Remember
- System.debug is not counted as a part of code coverage.
- As a part of best practice, we don’t write system.debug in apex class, we only use them for testing or debugging purpose but when our code is ready, we need to remove system.debug from the actual apex code.
- Test methods and test classes are not counted as a part of the apex code limit, which means we can write long test classes with more methods just to make sure all code is covered.
- Classes can also be deployed on 0% code coverage but overall coverage of production org after deploying the code must be 75%, otherwise, salesforce won’t let you deploy the code.
Syntax of Test Methods
static void testName(){
//code_block
}
static testMethod void testName(){
//code_block
}
Test Class Containing a Test Method
static void myTestMethod(){
//code_block
}
We can incorporate multiple test methods as necessary to enhance the code coverage of the Apex classes.