【问题标题】:How to unit test the default case of an enum based switch statement如何对基于枚举的 switch 语句的默认情况进行单元测试
【发布时间】:2010-12-22 02:18:21
【问题描述】:

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

【问题讨论】:

    标签: c# unit-testing mocking moq


    【解决方案1】:

    试试下面的

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

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

    【讨论】:

      【解决方案2】:

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

      Create((EnumType)200);
      

      【讨论】:

        【解决方案3】:

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

        (EnumType)(-1)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多