Monday, December 7, 2009

Code coverage and Enum types

Hi,

I've been trying really hard to achieve 100% code coverage on one of the projects I'm working on right now. Pretty much all my business code showed the desired code coverage right up to the point where I introduced enumeration.

First let me explain why I wanted to get to the 100% in the first place.

Whenever I'm writing code that should be covered by unit tests (which is pretty much always nowadays) I'd like to be reminded (by either the code coverage results in CI or by the IDE) that some of the edge cases have not been tested yet. I know this might sound bad in the first place because I should only write as much code as required to satisfy the test I wrote but still - there are cases where the business code I produced does a little bit more than what's in the test. So it's a good idea to keep the 100% test coverage at all times so that once it drops below this magic number I'll notice immediately that something has been skipped.

Back to enumerations.

Those guys contain synthetic methods generated by the compiler (like valueOf and values) that do exist in the byte code but have no corresponding lines in the code itself. This means that there's more that meets the eye from the code's perspective but the code coverage tools I use (Cobertura and EclEmma) know only about byte code and they couldn't care less if the method they are testing came from the code itself or if it was dynamically generated by the compiler.

To that end, whenever I use an Enum the overall coverage drops like stone which simply looks awful.



But there's hope! One line of stupid test and all is green again.

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








I admit that the actual value of this test is minimum but the real reason to do that is to allow yourself the luxury to always react on the drop of coverage below 100% instead of manually checking every time if what's missing is really something we don't care about.

I hope this helps.

2 comments:

Unknown said...

I ran into the same scenario wondering why my test coverage report showed missing coverage around an enum. Thanks for your article - you rock!

Abed Tony BenBrahim said...

Thanks for the article