关于C#:如何对基于枚举的switch语句的默认情况进行单元测试

How to unit test the default case of an enum based switch statement

我在工厂中有一个switch语句,该语句根据传入的枚举的值返回命令。类似:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public ICommand Create(EnumType enumType)
{
   switch (enumType)
   {
      case(enumType.Val1):
         return new SomeCommand();
      case(enumType.Val2):
         return new SomeCommand();
      case(enumType.Val3):
         return new SomeCommand();
      default:
         throw new ArgumentOutOfRangeException("Unknown enumType" + enumType);
   }
}

我目前对枚举中的每个值都有一个切换用例。对于每种情况,我都有单元测试。如何对默认情况下的错误进行单元测试?显然,目前我无法传递未知的EnumType,但谁又说将来不会更改。无论如何,仅出于单元测试的目的,我是否可以扩展或模拟EnumType?


尝试以下

1
2
Assert.IsFalse(Enum.IsDefined(typeof(EnumType), Int32.MaxValue);
Create((EnumType)Int32.MaxValue);

的确,您为"默认"案例选择的任何值都可能有一天成为有效值。因此,只需添加一个测试以确保它与您检查默认值的位置不同即可。


您可以将不正确的值转换为您的枚举类型-这不会检查。因此,例如,如果Val1到Val3为1到3,请传入:

1
(EnumType)(-1)

您可以将枚举的基础类型转换为枚举类型,以创建"无效"值。

1
Create((EnumType)200);