How to create a SortedList <Tkey, TValue> with AutoFixture

I tried creating SortedList<,>using AutoFixture, but it creates an empty list:

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

I came up with the following, which generates elements, but a little awkwardly:

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

It is not generic (strongly typed for intand string). I have two different ones TValue SortedListsto create.

Any best deals?

+4
source share
1 answer

This is similar to the AutoFixture function, which should be out of the box, so I added a problem for this .

Until then, you can do something like the following.

First create 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 });
    }
}

. , . 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);

.

+6

All Articles