我正在使用“类型安全的枚举模式”
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。
您可能确实想要测试任何接收到a的代码的路径Level
是:它适当地处理了null值(例如,通过throw ArgumentNullException
)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句