[英]How to unit test a switch statement with a dependency on Console
[英]How to unit test the default case of an enum based switch statement
我在工厂中有一个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);
}
}
我目前为枚举中的每个值都有一个switch case。 我对每种情况都进行了单元测试。 如何对默认情况下的错误进行单元测试? 显然,目前我无法传递一个未知的EnumType,但是谁说这将来不会改变。 无论如何我是否可以纯粹为了单元测试而扩展或模拟EnumType?
请尝试以下方法
Assert.IsFalse(Enum.IsDefined(typeof(EnumType), Int32.MaxValue);
Create((EnumType)Int32.MaxValue);
确实,您为“默认”案例选择的任何值都可能有一天成为有效值。 因此,只需添加一个测试,以确保它不会在您检查默认值的同一位置。
您可以为枚举类型转换不正确的值 - 这不会检查。 因此,如果Val1到Val3例如是1到3,则传入:
(EnumType)(-1)
您可以将枚举的基础类型强制转换为枚举类型,以创建“无效”值。
Create((EnumType)200);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.