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

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

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

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天全站免登陆