Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何对基于枚举的switch语句的默认情况进行单元测试_C#_Unit Testing_Mocking_Moq - Fatal编程技术网

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

C# 如何对基于枚举的switch语句的默认情况进行单元测试,c#,unit-testing,mocking,moq,C#,Unit Testing,Mocking,Moq,我在工厂中有一个switch语句,它根据传入的枚举值返回一个命令。比如: public ICommand Create(EnumType enumType) { switch (enumType) { case(enumType.Val1): return new SomeCommand(); case(enumType.Val2): return new SomeCommand(); case(enumType

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

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?

尝试以下方法

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

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

您可以将枚举的基础类型强制转换为枚举类型,以创建“无效”值


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

(EnumType)(-1)
(EnumType)(-1)