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

查看:34
本文介绍了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:

  • 您可以通过将单元测试与它们正在测试的类放在同一个包中来测试受保护和包范围的方法.这是一种相当普遍的做法.
  • 您可以通过创建被测类的子类来测试另一个包中单元测试中受保护的方法,该子类将您要测试的公共方法覆盖,并让这些覆盖的方法使用 super 关键字调用原始方法.通常,这个测试子类"将是执行测试的 JUnit TestCase 类中的一个内部类.在我看来,这有点棘手,但我已经做到了.

希望这会有所帮助.

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

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