我试图从某些枚举类型的值集中排除某些枚举值,例如Unknown
和。Uninitialized
我可以看到它Enums
是使用给定类型EnumGenerator
的所有可能Enum
值的集合以循环方式生成的Enum
。
基于该代码,我的第一个想法是构建一个ISpecimenBuilder
检查Type.IsEnum
并执行context.Resolve(request)
直到直到Resolve
返回不在排除列表中的值的对象。
问题是这给了我递归错误。在检查了源代码之后,我明白了原因-如果构建器处理了一个请求,然后Resolve
再次用相同的请求调用另一个,您将陷入无限循环。
但是由于它EnumGenerator
是不可扩展的,而且我无法弄清楚如何拦截构建链,因此我很困惑如何解决此问题。
您可以创建一个自定义的标本生成器,该标本生成器使用现有的标本生成器,EnumGenerator
但跳过不需要的值。在本样本中,我specimen.ToString()
故意使用该方法,以便不与任何特定enum
类型链接:
public class ExcludeUnknownEnumGenerator : ISpecimenBuilder { private readonly EnumGenerator _enumGenerator = new EnumGenerator(); public object Create(object request, ISpecimenContext context) { var enumType = request as Type; if (enumType == null || !enumType.IsEnum) { return new NoSpecimen(); } var namesEnumerator = Enum.GetNames(enumType).GetEnumerator(); while (namesEnumerator.MoveNext()) { var specimen = _enumGenerator.Create(request, context); if (specimen.ToString() != "Unknown" && specimen.ToString() != "Uninitialized") { return specimen; } } throw new ObjectCreationException( "AutoFixture was unable to create a value for " + enumType.FullName + " since it is an enum containing either no values or " + "ignored values only ('Unknown' and 'Uninitialized'). " + "Please add at least one valid value to the enum."); } } public enum EnumWithUnknown { Known, Unknown, Wellknown, Uninitialized }
以下代码显示enum
不带Unknown
和Uninitialized
状态的值:
var fixture = new Fixture(); fixture.Customizations.Insert(0, new ExcludeUnknownEnumGenerator()); Console.Out.WriteLine("result = {0}", fixture.Create()); Console.Out.WriteLine("result = {0}", fixture.Create ()); Console.Out.WriteLine("result = {0}", fixture.Create ()); Console.Out.WriteLine("result = {0}", fixture.Create ()); *** ConsoleOutput *** result = Known result = Wellknown result = Known result = Wellknown