Testing the typesafe enum pattern in C#

拈花ヽ惹草 提交于 2019-12-24 18:03:50

问题


I am utilizing the "typesafe enum pattern"

public class Level
{
    public static readonly Level Low = new Level(0, "Low");
    public static readonly Level Medium = new Level(1, "Medium");
    public static readonly Level High = new Level(2, "High");

    private int _value;
    private string name;

    private Level(int value, string name)
    {
        _value=value;
        _name=name;
    }
}

For testing purposes I need to create an invalid Level which I do with reflection.

int id = -1;
string value = "invalid";
var constructor = typeof(Level).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] {typeof(int), typeof(string)}, null);
var invalidLevel = (Level)constructor.Invoke(new object[] {id, value});

Using reflection to access the private constructor seems.... wrong to me. Is there a better way to make an invalid Level?


回答1:


For testing purposes I need to create an invalid Level

Why? The point of the enum pattern here is to stop there from ever being an invalid level.

Trying to test this being broken is like trying to test that a method is type-safe by calling it via reflection with the wrong number of arguments. Basically, you shouldn't be trying to test this path IMO.

One path you probably do want to test for any code which receives a Level is that it handles a null value appropriately (e.g. by throwing ArgumentNullException).




回答2:


Unit testing is about testing the public method/properties of a class (i.e. exercising the public API). As far as your class do not expose public ctor, you shouldn't need a test for that.



来源:https://stackoverflow.com/questions/17548752/testing-the-typesafe-enum-pattern-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!