Emma coverage on Enum types

浪子不回头ぞ 提交于 2019-12-03 04:43:12

问题


I'm running EclEmma, the Emma plugin for Eclipse, and the coverage report shows only partial coverage for an Enum I've defined, even though it shows the only value in the Enum as being covered. I'm assuming that there is a coverage gap for the implied methods that back the Enum, but I'm not quite sure.

For example, with this Enum, EclEmma highlights everything in green, except for the package declaration:

package com.blah;

public enum UserRole {
 HAS_ACCESS
}

If I pull up the coverage details for the class, I see this:

My question is, what is the best way to get 100% coverage on my Enum classes using EclEmma?


回答1:


What you're seeing is some hidden bytecode being generated due to an enumeration.

To get rid of this issue, add a call to the values() and valueOf() methods in the enum, as mentioned earlier by Carl Manaster and Peter Lawrey.




回答2:


I agree with other posters that 100% code coverage can be misguided. But I have to admit to the satisfaction of getting 100% coverage on newly written core code.

Fortunately since all enums extend the same 'class', you can achieve your 100% with a little help from your friend reflection.

Just add the following static method in a class for your testers to call, using [EnumTypeName].class as a parameter.

  public static void superficialEnumCodeCoverage(Class<? extends Enum<?>> enumClass) {
    try {
      for (Object o : (Object[])enumClass.getMethod("values").invoke(null)) {
        enumClass.getMethod("valueOf", String.class).invoke(null, o.toString());
      }
    }
    catch (Throwable e) {
      throw new RuntimeException(e);
    }
  }

Assuming this static function was implemented in a class called "Shared", you would only need to include this line for each enum:

Shared.superficialEnumCodeCoverage(UserRole.class);

The key word is 'superficial'.




回答3:


We ran into a similar issue where the compiler generated methods on enumerations, like values(), typically were not being called in our test code. We worked around the problem by filtering the numbers of our enum objects out of our final report.

This is why I don't like using code coverage as a measure of completeness. When I think of a better metric, I'll let you know. :)



来源:https://stackoverflow.com/questions/4512358/emma-coverage-on-enum-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!