C# 如何创建分类列表<;Tkey,TValue>;带自动夹具

C# 如何创建分类列表<;Tkey,TValue>;带自动夹具,c#,unit-testing,autofixture,C#,Unit Testing,Autofixture,我尝试使用AutoFixture创建一个SortedList,但它创建了一个空列表: var list = fixture.Create<SortedList<int, string>>(); var list=fixture.Create(); 我提出了以下生成项目的方法,但有点笨拙: fixture.Register<SortedList<int, string>>( () => new SortedList<int, st

我尝试使用AutoFixture创建一个
SortedList
,但它创建了一个空列表:

var list = fixture.Create<SortedList<int, string>>();
var list=fixture.Create();
我提出了以下生成项目的方法,但有点笨拙:

fixture.Register<SortedList<int, string>>(
  () => new SortedList<int, string>(
    fixture.CreateMany<KeyValuePair<int,string>>().ToDictionary(x => x.Key, x => x.Value)));
fixture.Register(
()=>新分类列表(
fixture.CreateMany().ToDictionary(x=>x.Key,x=>x.Value));
它不是泛型的(强类型为
int
string
)。我有两个不同的
TValue
sortedList
要创建


还有更好的建议吗?

这似乎是AutoFixture应该具备的现成功能,所以我添加了

不过,在此之前,您可以执行以下操作

首先,创建一个
ISpecimenBuilder

public class SortedListRelay : ISpecimenBuilder
{
    public object Create(object request, ISpecimenContext context)
    {
        var t = request as Type;
        if (t == null ||
            !t.IsGenericType ||
            t.GetGenericTypeDefinition() != typeof(SortedList<,>))
            return new NoSpecimen();

        var dictionaryType = typeof(IDictionary<,>)
            .MakeGenericType(t.GetGenericArguments());
        var dict = context.Resolve(dictionaryType);
        return t
            .GetConstructor(new[] { dictionaryType })
            .Invoke(new[] { dict });
    }
}
这个测试通过了

var fixture = new Fixture();
fixture.Customizations.Add(new SortedListRelay());

var actual = fixture.Create<SortedList<int, string>>();

Assert.NotEmpty(actual);