3

It is possible to guarantee a unique instance of an object with enums in Java as following:

public enum EmmaTest {

    ;

    public static int someStaticMethod() {
        return 33;
    }

}

How can one implement 100% Emma test coverage on such objects? Is it possible? Or is it possible to tell Emma to ignore some methods?

The best I can get is:

enter image description here

Jérôme Verstrynge
  • 57,710
  • 92
  • 283
  • 453
  • 1
    Lack of special handling for `enum` seems like a flaw that Emma should correct. However, 100% test coverage is likely to be counterproductive for you. – erickson Aug 11 '11 at 16:43
  • It is not so much the 100% I am interested in than the red I want to get rid of in the report. – Jérôme Verstrynge Aug 11 '11 at 16:46

2 Answers2

7

Adding the line below to any test fixed it the code coverage for me:

MyEnum.valueOf(MyEnum.VALUE.toString());

Clearly the debate on the value of this is different to the actual solution. I too have a requirement for 100% coverage which was falling down due to the constructor of the enum not being called. Adding the above to a test resolved that for me without any clever reflection etc...

theINtoy
  • 3,388
  • 2
  • 37
  • 60
2

Your EmmaTest is not a singleton. There is 0 instance of EmmaTest, so its constructor is never used, and there is no way to call valueOf with a valid value.

BTW: do you really fear that valueOf or the default constructor might have a bug? Why do you want 100% coverage?

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • ok, so are you saying it is not possible to obtain 100% test coverage, because there is no way to create an instance of the enum? – Jérôme Verstrynge Aug 11 '11 at 16:39
  • I am not scared of a bug in valueOf, it is just that Emma is reporting it as untested and it is untestable. Now, I could create a dummy enum value as a workaround. I am wondering if there is a better solution. – Jérôme Verstrynge Aug 11 '11 at 16:44
  • 1
    I think you're perverting the enum concept to make a static utility class. I would just use a regular class with a private constructor for this. The private constructor would also never be called, but the code would be cleaner, IMHO. – JB Nizet Aug 11 '11 at 17:01
  • I agree, this is not exactly a singleton. I am pushing the concept described at http://stackoverflow.com/questions/70689/efficient-way-to-implement-singleton-pattern-in-java a little further. I can define static variables in the enum to imitate singletons (which I did not in the OP). Of course, I am loosing the usage of synchronized() by doing so. – Jérôme Verstrynge Aug 11 '11 at 17:21
  • I have managed to work around my issue with a dummy enum value. Thanks for the clarification. – Jérôme Verstrynge Aug 11 '11 at 17:22