【发布时间】:2013-07-09 12:56:32
【问题描述】:
我正在使用“类型安全枚举模式”
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;
}
}
为了测试目的,我需要创建一个无效的关卡,我用反射来做。
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});
使用反射访问私有构造函数似乎....对我来说是错误的。有没有更好的方法来制作无效的关卡?
【问题讨论】:
-
我真的不明白您为什么要使用反射验证无效的
Level?这对我来说似乎太过分了。如果你完全控制了这个库(即它没有在其他地方使用),这将永远不会发生,除非你自己做。如果没有,您的库的用户知道使用私有构造函数创建对象超出了您的库的范围
标签: c# unit-testing design-patterns testing nunit