PDI · Question #159
How should a developer write unit tests for a private method in an Apex class?
The correct answer is C. Use the TestVisible annotation. To write unit tests for a private method in an Apex class, a developer should apply the @TestVisible annotation to the private method.
Question
How should a developer write unit tests for a private method in an Apex class?
Options
- AUse the SeeAllData annotation.
- BAdd a test method in the Apex class.
- CUse the TestVisible annotation.
- DMark the Apex class as global.
How the community answered
(44 responses)- A2% (1)
- B5% (2)
- C91% (40)
- D2% (1)
Why each option
To write unit tests for a private method in an Apex class, a developer should apply the `@TestVisible` annotation to the private method.
The `@isTest(SeeAllData=true)` annotation grants test methods access to all organization data and is generally discouraged, as it does not address the accessibility of private methods.
Test methods must reside in separate test classes, not directly within the Apex class containing the private method.
The `@TestVisible` annotation allows test methods to access private or protected members (methods or variables) of an Apex class without altering their visibility or encapsulation for non-test code, making it the correct approach for testing internal logic.
Marking an Apex class as `global` changes its accessibility across namespaces and managed packages, but it does not inherently make its private methods accessible to test classes.
Concept tested: Testing private Apex methods using TestVisible.
Source: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_unit_test_private.htm
Topics
Community Discussion
No community discussion yet for this question.