I have an issue, I want to test this line of code:


The variable in my controller is:

private DataToCompare compareAnIssue ;

and the DataToCompare type is a public class in my controller that I use to compare some fields:

public class DataToCompare { 

I am trying to do it like this:

ApexPages.StandardController sc = new ApexPages.standardController();
ControllerName  controllerName = new ControllerName(sc);
controllerName.compareAnIssue = '';

The problem arrives in the last line, which throws this compile error:

Line x, Column y
Variable is not visible: controllerName.compareAnIssue

How I can increase this line's coverage?


3 Answers 3


You can't ordinarily "see" private members, but you can add @TestVisible to allow the unit test to see the variable:

@TestVisible DataToCompare compareAnIssue;

Then, your unit test can do stuff with it:

controller.compareAnIssue = new ControllerName.DataToCompare();

To access private variables, you can make use of TestVisible Annotation:

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

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

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
        // Perform some verification

Code is from this reference doc, read this document for more details.


You are trying to access a private class variable, compareAnIssue, outside of that class. Private variables are only accessible within the class they are declared in. There are two ways around this:

Make it public:

public DataToCompare compareAnIssue;

(Recommended) Keep it private, but use @TestVisible to allow access from test classes only.

@testVisible private DataToCompare compareAnIssue;

In either case, your test code can access it like your example above. (Although of course setting it to a String wouldn't work right, since it's an instance of DataToCompare)

  • Test class will not work as written as compareAnIssue is an instance of DataToCompare not a string
    – Eric
    Commented Jan 20, 2017 at 12:47
  • Thank you to replied me, i solved for the visibility but how i can cast my variable in the string? i received the same error problem about illegal assignment.
    – Amiga 500
    Commented Jan 20, 2017 at 14:40

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .