模拟新的枚举值以测试开关中的默认情况
我正在尝试在检查枚举的开关中测试默认情况。我已经看过几篇文章并获得了此解决方案:
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);
}
但是,这给了我在Switch语句上的以下错误
Java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4
此答案的评论 https://stackoverflow.com/a/7233572/2696646 似乎描述了解决我问题的解决方案,但据我所知,我确实做到了。
这是我的枚举和切换:
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
}
有人可以向我解释我做错了什么吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论