Apex Developer Guide
Testing Apex
Let's talk about unit tests, data visibility for tests, and the tools that are available on the Lightning platform for testing Apex. We'll also describe testing best practices and a testing example.
To protect the privacy of your data, make sure that test error messages and exception details don’t contain any personal data. The Apex exception handler and testing framework can’t determine if sensitive data is contained in user-defined messages and details. To include personal data in custom Apex exceptions, we recommend that you create an Exception subclass with new properties that hold the personal data. Then, don’t include subclass property information in the exception's message string.
Note
-
Understanding Testing in Apex
-
What to Test in Apex
-
What Are Apex Unit Tests?
-
Understanding Test Data
Apex test data is transient and isn’t committed to the database. -
Run Unit Test Methods
To verify the functionality of your Apex code, execute unit tests. You can run Apex test methods in the Developer Console, in Setup, in the Salesforce extensions for Visual Studio Code, or using the API. -
Testing Best Practices
-
Testing Example
-
Testing and Code Coverage
The Apex testing framework generates code coverage numbers for your Apex classes and triggers every time you run one or more tests. Code coverage indicates how many executable lines of code in your classes and triggers have been exercised by test methods. Write test methods to test your triggers and classes, and then run those tests to generate code coverage information. -
Code Coverage Best Practices
Consider the following code coverage tips and best practices. -
Build a Mocking Framework with the Stub API
Apex provides a stub API for implementing a mocking framework. A mocking framework has many benefits. It can streamline and improve testing and help you create faster, more reliable tests. You can use it to test classes in isolation, which is important for unit testing. Building your mocking framework with the stub API can also be beneficial because stub objects are generated at runtime. Because these objects are generated dynamically, you don’t have to package and deploy test classes. You can build your own mocking framework, or you can use one built by someone else. -
Apex Integration Tests for Agentforce and Data 360 Services (Developer Preview)
Use Apex integration tests to write end-to-end tests that exercise real interactions between your Salesforce org and services such as Agentforce and Data 360. Unlike standard Apex unit tests, integration tests relax callout restrictions and transaction rollback semantics, so your tests can make real service calls, commit data mid-transaction, and make assertions on expected outcomes. As a developer preview feature, integration tests are available only in scratch orgs. You can’t run them in production orgs or during metadata deployments.