Salesforce | Why to use @TestVisible annotation

|
| By Webner

Problem: Why we use @TestVisible annotation for a private method and private variable of a Class in Salesforce?

Description: I have a situation where I want to call a private method of a class in the test class, whenever I tried to call the private method it throw an error that no such method exists.

Solution: @TestVisible annotation allow test methods to access private or protected members of another class

Code Sample:

public class updaterecord {
    @TestVisible private static string StatusOfCon = ‘Active’; // Private variable 
    // Private method
    @TestVisible private static void updateMethod(Contact con) {
        Update con;
    }
}

Test Class:
@isTest
private class Testupdaterecord {
    @isTest static void testup() {
    String stat = Testupdaterecord.recordNumber; // Accessing private variable annotated with TestVisible
    Contact conn1 = new Contact();
    conn1.firstname = ”test”;
    conn1.status = stat;
    Testupdaterecord.updateRecord(conn1); // Accessing private method annotated with TestVisible
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *