Andrew Robie
Andrew Robie

Reputation: 303

Force Switch Default In Java Enum

Say I created an enum, for example below:

public enum MyEnum {
    A,
    B,
    C;
}

And have a switch statement (like below) where each enum value has a case statement, but I also included a default to throw an IllegalArgumentException. (In case a new enum value gets added to make it more likely that someone will notice something going wrong with that case statement if the new value were to get passed. My thinking is Exceptions are much more noticeable than logs or trying to handle the new case.)

switch(myEnum) {
    case A:
        //do something
        break;
    case B:
        //do something
        break;
    case C:
        //do something
        break;
    default:
        throw new IllegalArgumentException("Unrecognized enum type!");
}

Unless I'm missing something, in theory, the default should be unreachable without the addition of a new enum value or altering the switch statement.

So what I was wondering is if I'm writing JUnit tests for code coverage, is there a way to force the switch to hit the default statement without updating application code?

Upvotes: 6

Views: 3444

Answers (1)

Andrew Robie
Andrew Robie

Reputation: 303

It is not possible to force Java to hit a default case in a switch statement as described in the question, i.e. one where all enum values have a case which breaks out of the switch.

Upvotes: 2

Related Questions