views:

172

answers:

3

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);
   }
}

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?

+8  A: 

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.

JaredPar
A: 

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

Create((EnumType)200);
bdukes
A: 

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)
David M