Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emma coverage on Enum types

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:

alt text

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

like image 227
Javid Jamae Avatar asked Dec 22 '10 18:12

Javid Jamae


People also ask

How do you validate enums?

Validating That a String Matches a Value of an Enum For this, we can create an annotation that checks if the String is valid for a specific enum. This annotation can be added to a String field and we can pass any enum class.

Are enums better than strings?

The advantage of an enum is that they are a strongly typed value. There are no advantages to using strings.

Can enums have member variables?

You can't use member variables or constructors in an enum.

What are enumerations enums in Java?

An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.


2 Answers

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.

like image 53
deterb Avatar answered Sep 17 '22 15:09

deterb


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'.

like image 20
Darren Avatar answered Sep 16 '22 15:09

Darren