7

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?

user963935
  • 493
  • 4
  • 20

3 Answers3

4

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>>();
user963935
  • 493
  • 4
  • 20
0

Something like

fixture.Register((List<string> l) => l.ToImmutableList());

ought to do it.

Mark Seemann
  • 225,310
  • 48
  • 427
  • 736
  • Works great for string! Is it any way to make it generic for all types? – user963935 Jul 18 '17 at 13:04
  • 1
    @user963935 That's a bit more involved, but you should be able to write an `ISpecimenBuilder` like [ListRelay](https://github.com/AutoFixture/AutoFixture/blob/master/Src/AutoFixture/Kernel/ListRelay.cs). – Mark Seemann Jul 18 '17 at 15:25
0

Looks like there is a nuget package to solve this:

https://www.nuget.org/packages/AutoFixture.Community.ImmutableCollections/#

eflles
  • 6,606
  • 11
  • 41
  • 55