Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoFixture: how to create polymorphic objects with ISpecimenBuilder

Tags:

c#

autofixture

I am a little at a loss as to how to code this better. The use of reflection to obtain the Create<T> on the specimen context is terrible. Sadly CreateAnonymous is deprecated... So I can't think of a better way.

IX is an interface, and the specimen builder is creating random instances of concrete classes implementing IX for testing purposes.

/// <summary>
/// A specimen builder that creates random X messages.
/// </summary>
public class XMessageBuilder : ISpecimenBuilder
{
    // for brevity assume this has types implementing IX
    private readonly Type[] types;
    private readonly Random random = new Random();

    // THERE MUST BE A BETTER WAY TO DO THIS?
    // CreateAnonymous is deprecated :-(
    public IX CreateSampleMessage(ISpecimenContext context)
    {
        var rm = this.types.ElementAt(this.random.Next(0, this.types.Length));
        var method = typeof(SpecimenFactory).GetMethod("Create", new[] { typeof(ISpecimenContext) });
        var generic = method.MakeGenericMethod(rm);
        var instance = generic.Invoke(null, new object[] { context });
        return (IX)instance;
    }

    public object Create(object request, ISpecimenContext context)
    {
        var parameter = request as ParameterInfo;
        if (parameter == null)
            return new NoSpecimen();

        if (parameter.ParameterType == typeof(IX))
            return this.CreateSampleMessage(context);

        if (parameter.ParameterType == typeof(IX[]))
        {
            var array = new IX[10];
            for (int index = 0; index < array.Length; index++)
                array[index] = this.CreateSampleMessage(context);
            return array;
        }

        return new NoSpecimen();
    }
like image 956
Jim Avatar asked Aug 11 '26 19:08

Jim


1 Answers

Something like this ought to work:

public IX CreateSampleMessage(ISpecimenContext context)
{
    var rm = this.types.ElementAt(this.random.Next(0, this.types.Length));
    return (IX)context.Resolve(rm);
}

(I haven't tried to compile and run a repro, though, so I may have made an error somewhere.)

like image 178
Mark Seemann Avatar answered Aug 13 '26 09:08

Mark Seemann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!