I'm trying to test a default case in a switch that checks an enum. I've seen a few posts and got to this solution:
int nValues = EnumType.values().length;
try (MockedStatic<EnumType> mocked = mockStatic(EnumType.class)) {
val UNSUPPORTED = mock(EnumType.class);
doReturn(nValues).when(UNSUPPORTED).ordinal();
doReturn(nValues).when(UNSUPPORTED).getValue();
doReturn("UNSUPPORTED").when(UNSUPPORTED).name();
mocked.when(EnumType::values).thenReturn(new EnumType[] {
EnumType.A,
EnumType.B,
EnumType.C,
EnumType.D,
UNSUPPORTED});
assertThatThrownBy(() -> mapper.callSwitch(UNSUPPORTED))
.isInstanceOf(CustomException.class);
}
However this gives me the following error on the switch statement
Java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4
One of the comments on this answer https://stackoverflow.com/a/7233572/2696646 seems to describe a solution to my problem, but as far as I can see I did exactly that.
Here's my enum and switch:
public enum EnumType{
A(0),
B(1),
C(2),
D(3);
}
switch (status) {
case A:
return "aaaa";
case B:
return "bbbb";
case C:
return "cccc";
case D:
return "dddd";
default:
// throw some custom exception
}
Can anyone explain to me what I'm doing wrong?