Programming against an enum in a switch statement, is this your way to do?

前端 未结 12 2280
青春惊慌失措
青春惊慌失措 2020-12-24 09:15

Look at the code snippet:

This is what I normally do when coding against an enum. I have a default escape with an InvalidOperationException (I do not use ArgumentExc

12条回答
  •  执念已碎
    2020-12-24 10:14

    I don't like this approach because the default case is untestable. This leads to reduced coverage in your unit tests, which while isn't necessarily the end of the world, annoys obsessive-compulsive me.

    I would prefer to simply unit test each case and have an additional assertion that there are only four possible cases. If anyone ever added new enum values, a unit test would break.

    Something like

    [Test]
    public void ShouldOnlyHaveFourStates()
    {
        Assert.That(Enum.GetValues( typeof( DrivingState) ).Length == 4, "Update unit tests for your new DrivingState!!!");
    }
    

提交回复
热议问题