+ Start a Discussion
bs881026bs881026 

how to access the private members of a class

Hi,

How can we access the private members of our class in the test class, if it is an independent test class.

Thanks,
 
Amit VaidyaAmit Vaidya
Hi,

Please refer the below snippet:
 
public class DemoClass {
    // Private member variable
    @TestVisible private Integer demoFld = 0;
}

// Test class for DemoClass
@isTest
private class DemoClassTest {

    //Test Method
    static TestMethod void demoTest() {
        DemoClass dmo = new DemoClass ();
		//Access Private variable
        dmo.demoFld = 123;
    }
}

Thanks,
Amit
JyothsnaJyothsna (Salesforce Developers) 
Hi,

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.

Apex Class:​
public class TestVisibleExample {
    // Private member variable
    @TestVisible private static Integer recordNumber = 1;

    // Private method
    @TestVisible private static void updateRecord(String name) {
        // Do something
    }
}

This is the test class that uses the previous class. It contains the test method that accesses the annotated member variable and method.​
Test Class:
 
@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
    }
}


Hope this helps you!
Best Regards,
Jyothsna