JUnit:仅使用静态方法测试辅助类 [英] JUnit: testing helper class with only static methods

查看:27
本文介绍了JUnit:仅使用静态方法测试辅助类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在测试一个仅使用 JUnit4 和 Cobertura 的静态方法的辅助类.测试方法是一项简单的任务,并且已经完成.

I am testing a helper class with only static methods with JUnit4 and Cobertura. Testing methods was easy task and is done already.

但是,cobertura 表明该类没有被测试完全覆盖,因为它没有在任何地方实例化.

However, cobertura shows that the class is not covered by tests completely, as it is not instantiated anywhere.

我不想创建这个类的实例(它是一个帮助类),所以第一个解决方案是隐藏构造函数(这通常是帮助类的好方法).

I don't want to create an instance of this class (it is a helper class), so first solution is to hide constructor (which is generally good approach for helper class).

然后 cobertura 抱怨空的私有构造函数没有被测试覆盖.

Then cobertura complains that the empty private constructor is not covered by tests.

对于这种情况,是否有任何解决方案可以实现 100% 的代码覆盖率?

Is there any solution to achieve 100% code coverage for such situation?

顶层管理需要代码覆盖率(在这种情况下),因此对我来说,获得 100% 的特定课程非常有帮助.

Code coverage is required from top level management (in this case), so for me obtaining 100% for this particular class is quite helpful.

推荐答案

有几种解决方案:

  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.

这篇关于JUnit:仅使用静态方法测试辅助类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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