Jam*_*Hay 21 c# unit-testing moq mocking
我在工厂中有一个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);
}
}
Run Code Online (Sandbox Code Playgroud)
我目前为枚举中的每个值都有一个switch case.我对每种情况都进行了单元测试.如何对默认情况下的错误进行单元测试?显然,目前我无法传递一个未知的EnumType,但是谁说这将来不会改变.无论如何我是否可以纯粹为了单元测试而扩展或模拟EnumType?
Jar*_*Par 28
请尝试以下方法
Assert.IsFalse(Enum.IsDefined(typeof(EnumType), Int32.MaxValue);
Create((EnumType)Int32.MaxValue);
Run Code Online (Sandbox Code Playgroud)
确实,您为"默认"案例选择的任何值都可能有一天成为有效值.因此,只需添加一个测试,以确保它不会在您检查默认值的同一位置.
Dav*_*d M 10
您可以为枚举类型转换不正确的值 - 这不会检查.因此,如果Val1到Val3例如是1到3,则传入:
(EnumType)(-1)
Run Code Online (Sandbox Code Playgroud)