junit& java:测试非公共方法 [英] junit & java : testing non-public methods

查看:107
本文介绍了junit& java:测试非公共方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JUnit只会在我的班级中测试那些公开的方法。如何对非(即私有,受保护)的进行junit测试?

JUnit will only test those methods in my class that are public. How do I do junit testing on the ones that are not (i.e., private, protected)?

我可以通过不使用junit来测试它们,但我想知道junit标准方法是什么。

I can test them by not using junit, but I was wondering what the junit standard method was.

推荐答案

关于单元测试的一个思想学派说你应该只能测试公共方法,因为你应该只对你的公共API进行单元测试,这样做,你应该是覆盖非公开方法中的代码。你的旅费可能会改变;我发现有时候会出现这种情况,有时候并非如此。

One school of thought about unit testing says that you should only be able to test public methods, because you should only be unit-testing your public API, and that by doing so, you should be covering the code in your non-public methods. Your mileage may vary; I find that this is sometimes the case and sometimes not.

有了这样的说法,有几种方法可以测试非公开方法:

With that said, there are a couple of ways to test non-public methods:


  • 您可以通过将单元测试与他们正在测试的类放在同一个包中来测试protected和package-scope方法。这是一种相当常见的做法。

  • 您可以通过创建被测试类的子类来覆盖要测试为public的方法,从而在另一个包中的单元测试中测试受保护的方法,以及使用这些重写方法使用super关键字调用原始方法。通常,这个测试子类将是执行测试的JUnit TestCase类中的内部类。在我看来,这有点多哈,但我已经做到了。

希望这会有所帮助。

这篇关于junit& java:测试非公共方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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