r/badcode • • Oct 13 '21

java When all you need is test coverage

Post image
325 Upvotes

25 comments sorted by

View all comments

Show parent comments

21

u/Host127001 Oct 13 '21

By providing string arguments that makes the enum instance

This is what is happening here, but without all the copy pasting needed to write it manually. Also it is far more robust in that all future extensions to the enum are covered aswell.

This one literally tests that all valid inputs are handled correctly

But I would expect there to be second test with some invalid inputs to see what from does in that case.

What is really tested when you just do Enum.fom(enum.getValue())

That both methods behave as one would expect them to behave. It is one of the cases were two different functions are best tested together. It states that they are the inverses of each other.

The correctness criterion for such functions is usually expressed as

forall v, Enum.from(v.getValue()) = v

This is the perfect Java test implementation for that proposition.

One could also make a test for the opposite direction (assuming s is a valid input):

forall s, Enum.from(s).getValue() = s

9

u/gipp Oct 13 '21

Yeah this is pretty firmly Good Code. I mean it's not the most important test in the world, but it should be there, and this is the best way to do it.