模拟新的枚举值以测试开关中的默认情况

发布于 2025-01-31 13:52:49 字数 1265 浏览 0 评论 0原文

我正在尝试在检查枚举的开关中测试默认情况。我已经看过几篇文章并获得了此解决方案:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文