Newer Version Available

This content describes an older version of this product. View Latest

TestVisible Annotation

Use the TestVisible annotation to allow test methods to access private or protected members of another class outside the test class. These members include methods, member variables, and inner classes. This annotation enables a more permissive access level for running tests only. This annotation doesn’t change the visibility of members if accessed by non-test classes.

With this annotation, you don’t have to change the access modifiers of your methods and member variables to public if you want to access them in a test method. For example, if a private member variable isn’t supposed to be exposed to external classes but it should be accessible by a test method, you can add the TestVisible annotation to the variable definition.

This example shows how to annotate a private class member variable and private method with TestVisible.

1swfobject.registerObject("clippy.codeblock-0", "9");
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17public class TestVisibleExample {
18    // Private member variable
19    @TestVisible private static Integer recordNumber = 1;
20
21    // Private method
22    @TestVisible private static void updateRecord(String name) {
23        // Do something
24    }
25}    

This is the test class that uses the previous class. It contains the test method that accesses the annotated member variable and method.

1swfobject.registerObject("clippy.codeblock-1", "9");
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17@isTest
18private class TestVisibleExampleTest {
19    @isTest static void test1() {
20        // Access private variable annotated with TestVisible
21        Integer i = TestVisibleExample.recordNumber;
22        System.assertEquals(1, i);
23
24        // Access private method annotated with TestVisible
25        TestVisibleExample.updateRecord('RecordName');
26        // Perform some verification
27    }
28}