开发者

How to unit test the default case of an enum based switch statement

开发者 https://www.devze.com 2022-12-13 11:19 出处:网络
I have a switch statement in a factory that returns a command based on the value of the enum passed in. Something like:

I have a switch statement in a factory that returns a command based on the value of the enum passed in. Something like:

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);
   }
开发者_如何学C}

I currently have a switch case for each value in the enum. I have unit tests for each of these cases. How do I unit test that the default case throws an error? Obviously, at the moment I can't pass in an unknown EnumType but who's to say this won't be changed in the future. Is there anyway I can extend or mock the EnumType purely for the sake of the unit test?


Try the following

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

It's true that any value you pick for the "default" case could one day become a valid value. So simply add a test to guarantee it doesn't in the same place you check the default.


You can cast an incorrect value to your enum type - this doesn't check. So if Val1 to Val3 are 1 to 3 for example, pass in:

(EnumType)(-1)


You can cast the underlying type of the enum to the enum type, to create an "invalid" value.

Create((EnumType)200);
0

精彩评论

暂无评论...
验证码 换一张
取 消