在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);
}
}
及用法:
var fixture = new Fixture();
fixture.Customizations.Add(new ImmutableListSpecimenBuilder());
var result = fixture.Create<ImmutableList<int>>();
类似的东西
fixture.Register((List<string> l) => l.ToImmutableList());
应该这样做。
看起来有一个 nuget 包可以解决这个问题:
https://www.nuget.org/packages/AutoFixture.Community.ImmutableCollections/#
您只需为您的测试创建一个扩展并注册
ImmutableHashSet<string>
即可从 ImmutableHashSet<string>.Empty
创建。
public static class AutoFixtureExtensions
{
public static Fixture DefaultCustomizations(this Fixture autofixture)
{
autofixture.Register(() => ImmutableHashSet<string>.Empty);
return autofixture;
}
}
并在您的测试中使用它,如下所示:
var result = new Fixture().DefaultCustomizations().Create<ImmutableList<int>>();