Activity Forums Salesforce® Discussions What is @testVisible used for while testing an Apex class in Salesforce?

  • shradha jain

    Member
    August 3, 2018 at 5:21 am

    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.

  • Avnish Yadav

    Member
    August 3, 2018 at 6:24 am

    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.

  • Parul

    Member
    September 28, 2018 at 5:24 pm

    @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
    }
    }

  • Pantala

    Member
    May 3, 2022 at 1:04 pm

    hai sir

  • Pantala

    Member
    May 3, 2022 at 1:05 pm

    guest duplicate user name

Log In to reply.

Popular Salesforce Blogs