Unit Testing Enums – Should You Test Enum Values

enumtestingtype-systemsunit testing

If you have an enum with values only (no methods as one could do in Java), and this enum is part of the business definition of the system, should one write unit tests for it?

I was thinking that they should be written, even if they could seem simple and redundant I consider that what concerns the business specification should be made explicitly written in a test, whether it be with unit/integration/ui/etc. tests or by using the type system of the language as a testing method. Since the values that an enum (e.g. in Java) must have, from the point of view of the business, cannot be tested using the type system I think there should be a unit test for that.

This question isn't similar to this one since it doesn't address the same problem as mine. In that question there is a business function (savePeople) and the person is inquiring about the internal implementation (forEach). In there, there's a middle business layer (the function save people) encapsulating the language construct (forEach). Here the language construct (enum) is the one used to specify the behavior from a business standpoint.

In this case the implementation detail coincides with the "true nature" of the data, that is: a set (in the mathematical sense) of values. You could arguably use an immutable set, but the same values should still be present there. If you use an array the same thing must be done to test the business logic. I think the conundrum here is the fact that the language construct coincides very well with the nature of the data. I am not sure if I've explained myself correctly

Best Answer

If you have an enum with values only (no methods as one could do in Java), and this enum is part of the business definition of the system, should one write unit tests for it?

No, they are just state.

Fundamentally, the fact that you are using an enum is an implementation detail; that's the sort of thing that you might want to be able to refactor into a different design.

Testing enums for completeness is analogous to testing that all of the representable integers are present.

Testing the behaviors that the enumerations support, however, is a good idea. In other words, if you start from a passing test suite, and comment out any single enum value, then at least one test should fail (compilation errors being considered failures).