问题
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