Note that there are some explanatory texts on larger screens.

plurals
  1. POFor testing purposes, how to add an additional element to an enum at runtime?
    text
    copied!<p><strong>tl;dr:</strong> 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 <strong>not</strong> consider this a duplicate of <a href="https://stackoverflow.com/questions/478403/can-i-add-and-remove-elements-of-enumeration-at-runtime-in-java">"Can I add and remove elements of enumeration at runtime in Java"</a> 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.</p> <hr> <p>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 <code>default</code> case on a <code>switch</code> statement with an <code>enum</code> where all the enums are covered by the cases.</p> <blockquote> <p>enum Pet { CAT, DOG; }</p> </blockquote> <p>and then code like</p> <pre><code>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 ); </code></pre> <p>I <strong>need</strong> to have the <code>default</code> statement or <code>javac</code> will complain that final line is using <code>speak</code> which might not be initialized.</p> <p>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 <em>production</em> code for the purposes of <em>testing</em>. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload