tl;dr: How do I, at runtime -for the purpose of testing-, add another element to a enum? I'm sure there must be away using some byte manipulation library like how PowerMockito works etc. I do not consider this a duplicate of "Can I add and remove elements of enumeration at runtime in Java" because I'm willing to put up with the kind of byte-manipulation or class-loader hacks you wouldn't do in production code, because it's for a test.
I'm writing Java unit tests and running unit test coverage reports. The only lines I'm not able to reach are in the code where I have a default
case on a switch
statement with an enum
where all the enums are covered by the cases.
enum Pet { CAT, DOG; }
and then code like
final String speak;
switch( myPet ){
case CAT:
speak = "meow";
break;
case DOG:
speak = "ruff";
break;
default:
throw new IllegalArgumentException( "should not get here" );
}
System.out.println( speak );
I need to have the default
statement or javac
will complain that final line is using speak
which might not be initialized.
However, I cannot get that line covered because there are no other values, and I don't want to add an additional enum value to production code for the purposes of testing.