且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JUnit:仅使用静态方法测试助手类

更新时间:2023-11-19 23:35:46

有几种解决方案:


  1. 您可以添加公共构造函数并从测试中调用它。虽然它没有意义,但它也没有太大的伤害。

  1. You can add a public constructor and call it from a test. While it doesn't make sense, it also doesn't hurt (much).

创建一个虚拟静态实例(你可以在这里调用私有构造函数) 。丑陋,但你可以给该字段一个名称来传达你的意图( JUST_TO_SILENCE_COBERTURA 是个好名字。)

Create a dummy static instance (you can call the private constructor here). Ugly but you can give the field a name to communicate your intent (JUST_TO_SILENCE_COBERTURA is a good name).

您可以让测试扩展辅助类。那将本质上调用默认构造函数,但你的助手类不能再是 final

You can let your test extend the helper class. That will intrinsically call the default constructor but your helper class can't be final anymore.

我建议最后一种方法,特别是因为该课程不能 final 了。如果代码的使用者想要添加另一个辅助方法,他们现在可以扩展现有的类并接收一个句柄来获取所有辅助方法。这会创建一个辅助方法的耦合,它传达意图(这些属于一起) - 如果帮助程序类是 final

I suggest the last approach especially because the class can't be final anymore. If a consumer of your code wants to add another helper method, they can now extend the existing class and receive one handle to get to all helper methods. This creates a coupling of the helper methods which communicates the intent (these belong together) - which is impossible if the helper class is final

如果你想阻止用户意外地实例化帮助程序类,请将其设为 abstract ,而不是使用隐藏的构造函数。

If you want to prevent users to accidentally instantiate the helper class, make it abstract instead of using a hidden constructor.