如何使用AutoFixture创建SortedList <Tkey,TValue>

Sea*_*n B 4 c# unit-testing autofixture

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

var list = fixture.Create<SortedList<int, string>>();
Run Code Online (Sandbox Code Playgroud)

我想出了以下产生物品,但有点笨重:

fixture.Register<SortedList<int, string>>(
  () => new SortedList<int, string>(
    fixture.CreateMany<KeyValuePair<int,string>>().ToDictionary(x => x.Key, x => x.Value)));
Run Code Online (Sandbox Code Playgroud)

它不是通用的(强烈键入intstring).我有两个不同TValue SortedLists的创造.

有更好的建议吗?

Mar*_*ann 6

这看起来像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 });
    }
}
Run Code Online (Sandbox Code Playgroud)

这种实现只是一个概念证明.它在各个地方缺乏适当的错误处理,但它应该证明这种方法.它解决了一个IDictionary<TKey, TValue>context,并使用返回值(其被填充)来创建的实例SortedList<TKey, TValue>.

为了使用它,您需要告诉AutoFixture:

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

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

Assert.NotEmpty(actual);
Run Code Online (Sandbox Code Playgroud)

这个测试通过.