Here are the best practices for writing effective test classes in Apex, formatted with bullet points for clarity in the Salesforce domain:
Best Practices for Apex Test Classes
Annotate Test Classes with @isTest:All test classes must start with the @isTest annotation to indicate they are test classes.
Focus on Comprehensive Code Coverage (90%+):
Ensure at least 75% code coverage to deploy to production.
Aim for 90%+ coverage to account for all use cases.
Focus on testing all scenarios, including:
Positive Tests: Verify expected outcomes.
Negative Tests: Validate behavior with invalid inputs or conditions.
Bulk Tests: Test functionality with a large number of records (e.g., 200+).
Single Record Tests: Test with just one record to handle edge cases.
Use Assert Statements:Include assert statements to validate test results:
System.assert(condition, message)
System.assertEquals(expected, actual, message)
System.assertNotEquals(expected, actual, message)
Each test method should have at least one assert statement.
Leverage @testSetup:Use the @testSetup annotation to create reusable test data for all methods in the class. This reduces redundancy and improves maintainability.
Create a Test Factory Class:
Use a TestFactory class annotated with @isTest to create reusable methods for generating test data.
Exclude the factory class from the organization’s code size limit.
Avoid seeAllData=true:
Always set (seeAllData=false) to isolate test data from production data.
Salesforce objects such as User, Profile, Organization, RecordType, and others can be accessed without enabling seeAllData.
Use System.runAs for Record Sharing:Apex runs in system mode by default, ignoring user permissions and sharing rules. Use System.runAs to enforce user-specific permissions and sharing rules in tests.
Avoid Hardcoding IDs:
Never hardcode IDs in test classes or Apex classes.
Use dynamic methods like querying or the Test.loadData() method to reference required IDs.
Utilize Governor Limits:
Use Test.startTest() and Test.stopTest() to reset governor limits for the "act" phase of your test.
Test for governor limits explicitly using the Limits class.
Test Exception Handling:
Provide test data that triggers exceptions in the production code.
Assert the exception type and error message for accuracy.
Exercise Bulk Trigger Functionality:
Test trigger logic with at least 200 records to ensure bulk data processing functions correctly.
These practices ensure reliable, maintainable, and high-quality test classes in Apex, enhancing your Salesforce development process.
Kommentarer