我正在尝试从任何枚举类型的值集中排除某些枚举值,例如Unknown
和Uninitialized
。
我可以看到Enums
使用EnumGenerator
从给定Enum
类型的所有可能Enum
值的集合中以inode on wikipedia生成。
基于该代码,我的第一个想法是构建一个ISpecimenBuilder
来检查Type.IsEnum
并执行context.Resolve(request)
直到Resolve
返回一个不在排除名单。
问题是这给了我一个递归错误。在检查源代码之后,我明白了为什么 - 如果构建器处理请求并使用相同的请求再次调用另一个Resolve
,您将最终处于无限循环中。
但由于EnumGenerator
不可扩展,我无法弄清楚如何拦截构建链,我对如何解决这个问题感到难过。
答案 0 :(得分:4)
您可以创建使用现有EnumGenerator
的自定义Specimen Builder,但会跳过您不需要的值。在此示例中,我有意使用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<EnumWithUnknown>());
Console.Out.WriteLine("result = {0}", fixture.Create<EnumWithUnknown>());
Console.Out.WriteLine("result = {0}", fixture.Create<EnumWithUnknown>());
Console.Out.WriteLine("result = {0}", fixture.Create<EnumWithUnknown>());
*** ConsoleOutput ***
result = Known
result = Wellknown
result = Known
result = Wellknown