Activity › Forums › Salesforce® Discussions › What is @testVisible used for while testing an Apex class in Salesforce?
Tagged: Access Modifiers, Annotation, Apex Class, Inner Class, Private Method, Private Variable, Protected Variable, Test Method, Testing, TestVisible
-
What is @testVisible used for while testing an Apex class in Salesforce?
Posted by Prachi on August 2, 2018 at 2:01 PMWhat is @testVisible used for while testing an Apex class in Salesforce?
Pantala replied 4 years ago 5 Members · 5 Replies -
5 Replies
-
Hello Prachi,
TestVisible annotation allows test methods to access private or protected members of another class outside the test class. These members include methods, member variables, and inner 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.
Thanks.
- [adinserter block='9']
-
Hi Prachi,
For example, If you have an Apex class or controller, It has a Private or Protected variable or methods or inner classes. so you can’t access them in other classes. But using this @testVisible annotation in a Private or Protected variable or methods or inner classes safely expose them only for test classes.
Ex: In Apex class not in Test class:// Private variable
@TestVisible private static String accountName= ‘acme’;
// Private method
@TestVisible private static void showRecord(String name) {
// add something
}
access them in test class accustomed.Thanks.
-
@TestVisible Annotation.
This annotation enables a more permissive access level for running tests only. TestVisible annotation 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 example shows how to annotate a private class member variable and private method with TestVisible.
public class TestVisibleExample {
@TestVisible private static Integer recordNumber = 1;
@TestVisible private static void updateRecord(String name) {
}
}This is the test class that uses the previous class. It contains the test method that accesses the annotated member variable and method.
@isTest
private class TestVisibleExampleTest {
@isTest static void test1() {
// Access private variable annotated with TestVisible
Integer i = TestVisibleExample.recordNumber;
System.assertEquals(1, i);// Access private method annotated with TestVisible
TestVisibleExample.updateRecord(‘RecordName’);
// Perform some verification
}
}
Log In to reply.