[英]Testing the typesafe enum pattern in C#
我正在使用“类型安全的枚举模式”
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;
}
}
出于测试目的,我需要创建一个无效的Level(通过反射进行)。
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});
用反射来访问私有构造函数似乎....对我来说是错误的。 有没有更好的方法来使无效的水平?
为了测试,我需要创建一个无效的关卡
为什么? 这里的枚举模式的要点是从那里停止它成为无效级别。
尝试测试这种破坏是否就像通过通过反射使用错误数量的参数来调用某个方法来测试该方法是否类型安全。 基本上,您不应该尝试测试此路径IMO。
你可能要测试其接收的任何代码一条道路Level
是它适当地处理空值(例如,通过抛出ArgumentNullException
)。
单元测试是关于测试类的公共方法/属性(即,使用公共API)。 只要您的课程不公开公共ctor,就不需要为此进行测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.