AutoFixture 重复次数

AutoFixture RepeatCount

有没有办法从 ISpecimenBuilder 中知道 RepeatCount?我正在为某些参数名称创建一个新的样本生成器。基本上 Create 方法会询问参数名称,以防万一"myParamName",类型为e.g. "MyParamType" 它将 return 自定义对象。

这很完美,但是,如果参数类型是 IEnumerable{MyParamType},我想 "CreateMany"。问题是……有多少?

我无法调用 context.Resolve 或 context.CreateMany{MyParamType},原因很简单,因为它不会按照我需要的方式创建我的对象。示例:如果 MyParamType 是字符串,它不会创建我需要的格式化字符串。这正是我首先创建样本生成器的原因!:) 我也无法为 MyParamType 注册我的新样本生成器,因为我只需要针对特定​​名称的参数值请求进行此自定义。否则,我需要默认行为

提前致谢

The problem is...how many?

默认情况下为 3。您可以在创建新的 Fixture 实例时更改此参数:

  var fixture = new Fixture { RepeatCount = 4 };

我不完全确定这是否是您想要做的,但您不必担心在自定义样本生成器中处理对 IEnumerable<T> 的请求; AutoFixture 会将 automatically convert IEnumerable<T> 请求转化为 多个 T 请求,然后由您的样本构建器处理。

例如,假设我们有一个自定义样本生成器,它只是 return 值 "foo" 用于 string:

的所有请求
public class FooBuilder : ISpecimenBuilder
{
    public object Create(object request, ISpecimenContext context)
    {
        return request.Equals(typeof(string))
            ? (object)"foo"
            : new NoSpecimen();
    }
}

现在,这个测试通过了:

[Fact]
public void Should_return_all_foos_for_a_sequence_of_strings()
{
    var fixture = new Fixture { RepeatCount = 4 };
    fixture.Customizations.Insert(0, new FooBuilder());

    var many = fixture.Create<IEnumerable<string>>();

    Assert.Equal(4, many.Count());
    Assert.All(many, i => Assert.Equal("foo", i));
}

因为 AutoFixture 确保根据需要多次调用 FooBuilder 以满足请求。