Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 919
James Hay Avatar asked Dec 01 '09 16:12

James Hay


People also ask

Is default case always executed in switch?

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.

Is default case optional in switch?

3) The default statement is optional. Even if the switch case statement do not have a default statement, it would run without any problem.

Is it necessary to include default case in a switch statement?

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.

Can enum be used in switch case in C?

1) The expression used in switch must be integral type ( int, char and enum). Any other type of expression is not allowed.


2 Answers

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.

like image 129
JaredPar Avatar answered Sep 21 '22 15:09

JaredPar


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) 
like image 33
David M Avatar answered Sep 18 '22 15:09

David M