如何向私有构造函数添加测试覆盖率? [英] How to add test coverage to a private constructor?

查看:24
本文介绍了如何向私有构造函数添加测试覆盖率?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是代码:

package com.XXX;
public final class Foo {
  private Foo() {
    // intentionally empty
  }
  public static int bar() {
    return 1;
  }
}

这是测试:

package com.XXX;
public FooTest {
  @Test 
  void testValidatesThatBarWorks() {
    int result = Foo.bar();
    assertEquals(1, result);
  }
  @Test(expected = java.lang.IllegalAccessException.class)
  void testValidatesThatClassFooIsNotInstantiable() {
    Class cls = Class.forName("com.XXX.Foo");
    cls.newInstance(); // exception here
  }
}

工作正常,该类已经过测试.但是 Cobertura 说该类的私有构造函数的代码覆盖率为零.我们如何为这样的私有构造函数添加测试覆盖率?

Works fine, the class is tested. But Cobertura says that there is zero code coverage of the private constructor of the class. How can we add test coverage to such a private constructor?

推荐答案

嗯,有一些方法可以潜在地使用反射等——但这真的值得吗?这是一个永远不应该被调用的构造函数,对吗?

Well, there are ways you could potentially use reflection etc - but is it really worth it? This is a constructor which should never be called, right?

如果有一个注释或任何类似的东西可以添加到类中,以使 Cobertura 了解它不会被调用,请执行此操作:我认为不值得人为地添加覆盖范围.

If there's an annotation or anything similar that you can add to the class to make Cobertura understand that it won't be called, do that: I don't think it's worth going through hoops to add coverage artificially.

如果没有办法做到这一点,只需忍受略微减少的覆盖范围.请记住,覆盖范围是对有用的东西——你应该负责这个工具,而不是相反.

If there's no way of doing it, just live with the slightly reduced coverage. Remember that coverage is meant to be something which is useful to you - you should be in charge of the tool, not the other way round.

这篇关于如何向私有构造函数添加测试覆盖率?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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