如何让AutoFixture从多个TypeRelays中随机选择?

How to make AutoFixture choose from a number of TypeRelays at random?

我有一个抽象基础 class,比如说基础,还有一些派生的 classes,比方说 D1、D2、D3。

当收到 Base 请求时,如何设置 AutoFixture 随机选择 D1、D2、D3 之一?

为每个 D1、D2、D3 添加一个 TypeRelay 到 Fixture.Customizations 似乎让它总是选择第一个添加的。

能够拼凑出以下代码。如果由于某种原因其中一个请求失败,它将回退到指定的默认值,这样一个请求就应该是失败证明。它并没有完全使用TypeRelay,但效果本质上是一样的。

public class RandomCustomization<T> : ICustomization
{
    private readonly Type _defaultType;
    private readonly Type[] _types;
    public RandomCustomization(Type defaultType, params Type[] types)
    {
        _defaultType = defaultType;
        _types = types;
    }
    public void Customize(IFixture fixture)
    {
        fixture.Customize<T>(v => v.FromFactory(new RandomFactory(_defaultType, _types)));
    }
}

public class RandomFactory : ISpecimenBuilder
{
    private readonly Type _defaultType;
    private readonly Type[] _types;
    private readonly Random _ran = new Random();

    public RandomFactory(Type defaultType, params Type[] types)
    {
        _defaultType = defaultType;
        _types = defaultType.Concat(types).ToArray();
    }
    public object Create(object request, ISpecimenContext context)
    {
        var which = _types[_ran.Next() % _types.Length];
        var toret = context.Resolve(which);
        if (toret == null || toret is OmitSpecimen)
        {
            toret = context.Resolve(_defaultType);
        }
        return toret;
    }
}