gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 04:33:33 25 4
gpt4 key购买 nike

我在工厂中有一个 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);

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

关于c# - 如何对基于枚举的 switch 语句的默认情况进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1827430/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com