不存在的枚举值的单元测试? [英] Unit Test for Enum value that doesn't exist?

查看:28
本文介绍了不存在的枚举值的单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

先来一些示例代码...

Some example code first...

枚举:

public enum TestEnum {
   YES,
   NO
}

一些代码:

public static boolean WorkTheEnum(TestEnum theEnum) {
   switch (theEnum) {
      case YES:
         return true;
      case NO:
         return false;
      default:
         // throws an exception here
   }
}

问题:
TestEnum 是我从不同开发人员的不同代码中导入的东西.所以它实际上可以改变.对于这种情况,我想要一个单元测试来实际检查那个不存在的值.但我就是不知道如何用 Mockito 和 JUnit 来实现.

Problem:
The TestEnum is something I import from a different code of a different developer. So it actually could change. For this case I want to have a unit test that actually checks for that non existing value. But I simply don't know how to do it with Mockito and JUnit.

这部分当然不起作用:

@Test(expected=Exception.class)
public void DoesNotExist_throwsException() throws Exception {
    when(TestEnum.MAYBE).thenReturn(TestEnum.MAYBE);
    WorkTheEnum(TestEnum.MAYBE);
}

我发现了一个使用 PowerMock 的示例,但我无法让它与 Mockito 一起使用.

I found one example that usees PowerMock, but I couldn't get it to work with Mockito.

有什么想法吗?

推荐答案

一个简单的怎么样:

Set<String> expected = new HashSet<> (Arrays.asList("YES", "NO"));
Set<String> actual = new HashSet<>();
for (TestEnum e : TestEnum.values()) actual.add(e.name());
assertEquals(expected, actual);

(使用 HashSet 而不是 ArrayList 因为顺序无关紧要)

(using HashSet rather than ArrayList because order does not matter)

这篇关于不存在的枚举值的单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆