我们如何测试包私有类? [英] How can we test package-private class?

查看:23
本文介绍了我们如何测试包私有类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读Effective Java一书,在Item 13: Minimize the accessibility of classes and members,它提到:

I am reading book Effective Java, in Item 13: Minimize the accessibility of classes and members, it mentioned that:

为了便于测试,您可能想使类、接口或成员更易于访问.这在一定程度上是好的.为了测试它,可以将公共类包的私有成员设置为私有是可以接受的,但是将可访问性提高到更高的程度是不可接受的.换句话说,为了方便测试而将类、接口或成员作为包的导出 API 的一部分是不可接受的.

To facilitate testing, you may be tempted to make a class, interface, or member more accessible. This is fine up to a point. it is acceptable to make a private member of a public class package-private in order to test it, but it is not acceptable to raise the accessibility any higher than that. In other words, it is not acceptable to make a class, interface, or member a part of packages's exported API to facilitate testing.

我知道我们应该封装成员,对客户端隐藏信息,我们可以通过使用 setter 和 getter 访问类来测试它们,但是我应该如何理解使类包私有可访问,如果是,如何测试?

I know we should encapsulate members, hiding information from clients, we can test them by accessing the class with setters and getters, but How should I understand make class package-private accessible, if so How to test it?

推荐答案

基本上这意味着您的测试类应该与您的测试类驻留在同一个包中.这将使您的测试类和所有受包保护的成员和方法都可以访问您的测试类.这些类可能位于不同的根目录下:您的测试类可能位于 src/main/java/myrootpackage/first/second/MyClass.java 下,而您的测试类可能位于 src/下test/java/myrootpackage/first/second/MyClassTester.java.

Basically it means that your tester class should reside in the same package as your tested class. That would make your tested class and all package protected members and methods accessible to your testing class. The classes may be located under different roots: your tested class may be under src/main/java/myrootpackage/first/second/MyClass.java and your testing class may be located under src/test/java/myrootpackage/first/second/MyClassTester.java.

这篇关于我们如何测试包私有类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆