Making the private access modifier visible during test execution.

Whenever I got error  like below during test execution, I will go directly to the class and change the access modifier from private to public.It is not proper because each access modifier serve different purpose, so it is not quite acceptable to modify it just to get PASS for testing.Seem unacceptable but I did it a lot of times. *Evil smile*

But I accidentally find proper solution for this.I posted it in my company site, but I m thinking to share it here.We can use @TestVisible ... @TestVisible everyone.I don't  notice since when it available, but I just noticed it yesterday.Shame!

Well, let's start experiment it.I am using free edition sandbox to test this.You can find this free sandbox here.

This is my class, notice the private stuff.Private variable and method.

public class MyClass{
    // Private member variable
    @TestVisible private static Integer recordNumber = 1;

    // Private method
    @TestVisible private static void updateRecord(String name) {
       recordNumber =recordNumber +1;

Here the test class.

private class MyClassTest {
    @isTest static void test1() {
        // Access private variable annotated with TestVisible
        Integer i = MyClass.recordNumber;
        System.assertEquals(1, i);

        // Access private method annotated with TestVisible
        // Perform some verification

If you remove @TestVisible, and run the test class you will get the above error.So now instead of changing the access modifier, bear in mind to put @TestVisible whenever you have private stuff to be tested.

Do not reveal your secret just because you want to pass the exam!Keep some mysterious remain.

Please dig more info about @TestVisible here. Have a very nice day ahead. =) .


Popular Posts