Hello everyone, In this tutorial, I am going to explain @TestVisible annotation with code example. In this section, you can find a brief note on @TestVisible annotation with a simple example.
 


After completing this tutorial, you’ll able to:
  • Describe @TestVisible annotation.
  • How to use @TestVisible annotation.
 
What is @TestVisible annotation?
@TestVisible annotation allows test methods to access private or protected members of the apex class. These members can be methods, variables or inner classes. @TestVisible annotation enables a more permissive access level for running tests only. This annotation doesn’t impact the visibility of members if accessed by non-test classes. When you use this annotation, you don’t have to change the access modifiers of your methods and the member variable to the public while accessing them in a test method.

For Example:
This example shows how to access private class member variable and private method with help of @TestVisible annotation.
 
 public class TestVisibleClass {
    // Private member variable
    @TestVisible private static Integer recordCount = 1;

    // Private method
    @TestVisible private static void updateAccount(String name) {
        // Do something
    }
 } 
This is the test class that uses the previous class. It contains the test method that accesses the @TestVisible annotated private member variable and method
 @isTest
 private class TestVisibleClassTest {
    @isTest static void testExample() {
        // Access private variable annotated with TestVisible
        Integer i = TestVisibleClass.recordCount;
        System.assertEquals(1, i);

        // Access private method annotated with TestVisible
        TestVisibleClass.updateAccount('Someone');
        // Perform some verification
    }
 } 

See also:

Conclusion:
Hope you like this tutorial, for any query or suggestions please feel free to comment.
Thank you.