user2953119
user2953119

Reputation:

Providing package-private methods for testing?

I'm writing the following class:

public class MyClass{

    private final MyAnotherClass[][] anotherClasses;

    public MyClass(//args){
        //initialization
    }

    //...
}

I'd like to test this class, but wouldn't like to provide any methods exposing its iternal state (anotherClasses array in this case). The test is going to test the state of the array, so we have to access it.

Is it considering as a good practice to provide a method, say

MyAnotherClass[][] getAnotherClasses(){
    retun anotherClasses;
}

with package-private visibility to use it only for testing? I'm kind of not sure about that. We introduce some annoying coupling between the class and its test...

Maybe there's a better approach to deal with that?

Upvotes: 1

Views: 1370

Answers (1)

Andrei_N
Andrei_N

Reputation: 430

As already mentioned, it is not good practice to test non-public methods. But sometimes if it is really needed for me, I'm using @VisibleForTesting annotation from guava.

Upvotes: 2

Related Questions