简体   繁体   English

提供测试包的私有方法?

[英]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). 我想测试此类,但不希望提供任何暴露其固有状态的方法(在这种情况下为anotherClasses数组)。 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? 具有package-private可见性以用于测试? 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? 也许有更好的方法来解决这个问题?

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. 但是有时候,如果我真的需要它,我会使用来自番石榴的@VisibleForTesting批注。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM