在 System.Collections.Generic 中有一个非常有用的 ImmutableList。但是对于这种类型的 Autofixture 会抛出异常,因为它没有公共构造函数,它的创建方式类似于new List<string>().ToImmutableList()
. 如何告诉 AutoFixture 填充它?
感谢@Mark Seemann,我现在可以回答我的问题了:
public class ImmutableListSpecimenBuilder : ISpecimenBuilder
{
public object Create(object request, ISpecimenContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
var t = request as Type;
if (t == null)
{
return new NoSpecimen();
}
var typeArguments = t.GetGenericArguments();
if (typeArguments.Length != 1 || typeof(ImmutableList<>) != t.GetGenericTypeDefinition())
{
return new NoSpecimen();
}
dynamic list = context.Resolve(typeof(IList<>).MakeGenericType(typeArguments));
return ImmutableList.ToImmutableList(list);
}
}
Run Code Online (Sandbox Code Playgroud)
及用法:
var fixture = new Fixture();
fixture.Customizations.Add(new ImmutableListSpecimenBuilder());
var result = fixture.Create<ImmutableList<int>>();
Run Code Online (Sandbox Code Playgroud)