如何强制 AutoFixture 创建 ImmutableList
How to force AutoFixture to create ImmutableList
在System.Collections.Generic中有一个非常有用的ImmutableList。但是对于这种类型,Autofixture 会抛出异常,因为它没有 public 构造函数,它的创建方式类似于 new List<string>().ToImmutableList()
。如何告诉 AutoFixture 填充它?
类似
fixture.Register((List<string> l) => l.ToImmutableList());
应该这样做。
感谢@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>>();
看起来有一个 nuget 包可以解决这个问题:
https://www.nuget.org/packages/AutoFixture.Community.ImmutableCollections/#
在System.Collections.Generic中有一个非常有用的ImmutableList。但是对于这种类型,Autofixture 会抛出异常,因为它没有 public 构造函数,它的创建方式类似于 new List<string>().ToImmutableList()
。如何告诉 AutoFixture 填充它?
类似
fixture.Register((List<string> l) => l.ToImmutableList());
应该这样做。
感谢@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>>();
看起来有一个 nuget 包可以解决这个问题:
https://www.nuget.org/packages/AutoFixture.Community.ImmutableCollections/#