3

Possible Duplicate:
Mocking Java enum to add a value to test fail case

I have a switch statement that works on an enum. The "default" case of the switch is to throw a runtime exception. It's coded like this to trap the situation where someone adds a value to the enum but forgets to update the switch statement.

I want to test this execution path, but I am struggling to find a way of doing so without putting an unused enum value into my live code. Is this a misuse of enum, or is there an accepted way of writing this test?

Community
  • 1
  • 1
DaveH
  • 7,187
  • 5
  • 32
  • 53

1 Answers1

1

What I am thinking you could do to test this is have a test case where you basically get all values of your enum like

T[] allEnumValues = enumValue.getDeclaringClass().getEnumConstants();

or

T[] allEnumValues = enumType.values();

and then take each one and put it in the switch statement. If you get an exception you have a problem.

PS: Link to the getEnumConstants() method.

  • This isn't quite what I want but is an interesting approach. I actually WANT to pass in an enum value that does not exist in the switch statement so that I can prove that the RTE is thrown. ( My client is very keen on code coverage ..... ) – DaveH Jun 11 '12 at 14:27