在 C# 中测试类型安全的枚举模式 [英] Testing the typesafe enum pattern in C#
问题描述
我正在使用类型安全枚举模式"
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?
推荐答案
出于测试目的,我需要创建一个无效的关卡
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.
试图测试这个被破坏的情况就像试图通过使用错误数量的参数通过反射调用一个方法来测试它是否是类型安全的.基本上,您不应该尝试测试这条路径 IMO.
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.
对于接收Level
的任何代码,您可能确实想要测试的一条路径是它适当地处理空值(例如,通过抛出ArgumentNullException
代码>).
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
).
这篇关于在 C# 中测试类型安全的枚举模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!