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?
The default statement is executed if no case constant-expression value is equal to the value of expression . If there's no default statement, and no case match is found, none of the statements in the switch body get executed.
3) The default statement is optional. Even if the switch case statement do not have a default statement, it would run without any problem.
No it is not necessary of default case in a switch statement and there is no rule of keeping default case at the end of all cases it can be placed at the starting andd middle of all other cases.
1) The expression used in switch must be integral type ( int, char and enum). Any other type of expression is not allowed.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With