且构网

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

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

更新时间:2023-11-19 23:39:58

有几种解决方案:

  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

如果您想防止用户意外实例化辅助类,请使其抽象,而不是使用隐藏的构造函数.

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