AutoFixture:如何使用 ISpecimenBuilder 创建多态对象

AutoFixture: how to create polymorphic objects with ISpecimenBuilder

对于如何更好地编写代码,我有点不知所措。使用反射获取标本上下文中的 Create<T> 是很糟糕的。遗憾的是 CreateAnonymous 已被弃用...所以我想不出更好的方法。

IX 是一个接口,样本生成器正在创建具体 类 的随机实例,实现 IX 用于测试目的。

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

像这样的东西应该可以工作:

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

(不过,我还没有尝试编译和 运行 重现,所以我可能在某处犯了错误。)