Jacoco 无法覆盖仅包含静态方法的类。

huangapple go评论73阅读模式
英文:

Jacoco is not able to cover a class containing only static methods

问题

Jacoco无法覆盖仅包含静态方法的类。我在测试类中没有实例化该类,而是直接调用了静态方法进行测试。

public class DateUtil {
    final static String datePattern = "EEE MM/dd/yyyy";

    public static String convertToGMTDate(Date date) {
        DateFormat df = new SimpleDateFormat(datePattern, Locale.getDefault());
        df.setTimeZone(TimeZone.getTimeZone("GMT"));
        return df.format(date);
    }
}
class DateUtilTest {
    static DateUtil dateutil;
    
    @Test
    void convertToGMTDate() {
        Date date = new GregorianCalendar(2020, Calendar.FEBRUARY, 11).getTime();
        String stringDate = dateutil.convertToGMTDate(date);
        assertEquals("Tue 02/11/2020", stringDate);
    }
}

错误报告仅突出显示了类名"DateUtil",并报告其覆盖率为75%。如何才能使该类的覆盖率达到100%?

在测试方法中不实例化该类会降低覆盖率25%。这有何意义?这是JaCoCo的缺陷吗?

提前致谢!

英文:

Jacoco is not able to cover a class containing only static methods. I did not instantiate the class in the test class rather directly called the static method to test.

public class DateUtil {
final static String datePattern = "EEE MM/dd/yyyy";

public static String convertToGMTDate(Date date ) {
    DateFormat df = new SimpleDateFormat(datePattern, Locale.getDefault());
    df.setTimeZone(TimeZone.getTimeZone("GMT"));
    return df.format(date);
  }
}



class DateUtilTest {
static DateUtil dateutil;
@Test
void convertToGMTDate() {
    Date date = new GregorianCalendar(2020, Calendar.FEBRUARY, 11).getTime();
    String stringDate = dateutil.convertToGMTDate(date);
    assertEquals("Tue 02/11/2020)",stringDate);
}
   
}

The error report highlighted just the class name "DateUtil" and reported that its 75% covered. What to do for the class to cover completely 100%?

Not instantiating the class in test method, decreases the coverage by 25% here. How does it makes sense? Is it flaw with JaCoCo?

Thanks in advance!

答案1

得分: 14

“缺失”的覆盖率确实来自于默认构造函数。

由于您的 `DateUtil` 类只是一个实用(或辅助)类,请像这样添加一个私有构造函数:

    private DateUtil() {
        // 实用类
    }

(请注意,这种类通常也会被声明为 `final`)

然后,JaCoCo 应该期望其覆盖率达到100%。
英文:

The "missing" coverage is indeed from the default constructor.

Since your DateUtil class is just a Utility (or helper) class, add a private constructor to it, like so:

private DateUtil() {
    // Utility class
}

(note that such classes are also usually declared final)

JaCoCo should then expect it to be 100% covered.

huangapple
  • 本文由 发表于 2020年8月28日 23:42:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/63636979.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定