gpt4 book ai didi

c# - 如何强制 AutoFixture 创建 ImmutableList

转载 作者:行者123 更新时间:2023-12-03 19:38:03 26 4
gpt4 key购买 nike

在 System.Collections.Generic 中有一个非常有用的 ImmutableList。但是对于这种类型,Autofixture 会抛出异常,因为它没有公共(public)构造函数,它的创建方式类似于 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>>();

关于c# - 如何强制 AutoFixture 创建 ImmutableList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45096171/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com