Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force AutoFixture to create ImmutableList

Tags:

c#

autofixture

In System.Collections.Generic there is a very useful ImmutableList. But for this type Autofixture is throwing an exception because it doesn't have public constructor, it's being created like new List<string>().ToImmutableList(). How to tell AutoFixture to populate it?

like image 329
user963935 Avatar asked Jul 14 '17 06:07

user963935


1 Answers

So thanks to @Mark Seemann I can now answer my question:

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

And usage:

var fixture = new Fixture();
fixture.Customizations.Add(new ImmutableListSpecimenBuilder());
var result = fixture.Create<ImmutableList<int>>();
like image 175
user963935 Avatar answered Nov 15 '22 10:11

user963935