How to force AutoFixture to create ImmutableList
Asked Answered
L

4

8

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?

Leonteen answered 14/7, 2017 at 6:31 Comment(0)
L
6

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>>();
Leonteen answered 19/7, 2017 at 9:26 Comment(0)
S
1

You can just create an extension for your tests and register ImmutableHashSet<string> to be created from ImmutableHashSet<string>.Empty.

public static class AutoFixtureExtensions
{
    public static Fixture DefaultCustomizations(this Fixture autofixture)
    {
        autofixture.Register(() => ImmutableHashSet<string>.Empty);
        return autofixture;
    }
}

And use it in your tests like this:

var result = new Fixture().DefaultCustomizations().Create<ImmutableList<int>>();
Sthenic answered 23/10, 2023 at 9:22 Comment(0)
L
0

Something like

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

ought to do it.

Lieutenancy answered 14/7, 2017 at 7:29 Comment(2)
Works great for string! Is it any way to make it generic for all types?Leonteen
@Leonteen That's a bit more involved, but you should be able to write an ISpecimenBuilder like ListRelay.Lieutenancy
M
0

Looks like there is a nuget package to solve this:

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

Medellin answered 6/4, 2021 at 11:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.