JUnit测试私有变量? [英] JUnit Testing private variables?

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

问题描述

我已经被分配了一个单元测试的任务,该类是我从未直接使用过JUnit的类,因此严禁更改包中的代码.通常这不是问题,因为我们的大多数单元测试仅是为了功能和输入/输出一致性,而这可以简单地通过运行例程并检查其返回值来完成.

但是,有时需要检查类中的私有变量,或者直接编辑私有变量以检查某些内部行为.有没有一种方法可以通过单元测试的目的通过JUnit或任何其他方式获得这些访问权限,而无需实际更改原始源代码包中的任何代码?如果不是,那么程序员在现实世界中如何处理这个问题呢?在现实世界中,单元测试人员可能与编码人员不是同一个人?

解决方案

是的,您可以使用反射来访问私有变量.绝对不是一个好主意.

检查一下:

http://en.wikibooks.org/wiki/Java_Programming/Reflection/Accessing_Private_Features_with_Reflection

I have been assigned the task of unit testing a class that I never worked directly on with JUnit, and am strictly forbidden to change the code in the package. This is usually no issue, since most of our unit testing is just for functionality and input/output consistency, which can be done simply by running routines and checking their return values.

However, occasionally there is a need to check a private variable within the class, or directly edit a private variable to check some internal behavior. Is there a way to gain access to these, whether through JUnit or any other way, for the purpose of unit testing without actually changing any of the code in the original source package? And if not, how do programmers handle this issue in the real world where a unit tester may not be the same person as the coder?

解决方案

Yeah you can use reflections to access private variables. Altough not a good idea.

Check this out:

http://en.wikibooks.org/wiki/Java_Programming/Reflection/Accessing_Private_Features_with_Reflection

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

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