具有不同值的 AutoFixure Fixture.Build().With()

AutoFixure Fixture.Build().With() with different values

考虑 class

class A
{
    public class NestedA
    {
        public string StrWithInt { get; set; }

        public string Str1 { get; set; }

        public string Str2 { get; set; }
    }

    public List<NestedA> Items { get; set; }
}

我正在使用 AutoFixture 框架来生成具有随机内容的 class A 实例。
NestedA 的 class 属性 StrWithIntstring 类型,但它的值必须是数字,int 值。所以我正在使用 With() 方法来自定义生成。

我的代码如下所示:

Random r = new Random();
Fixture fixture = new Fixture();
fixture.Customize<A.NestedA>(ob =>
    ob.With(p => p.StrWithInt, r.Next().ToString())
);
var sut = fixture.Build<A>().Create();

foreach (var it in sut.Items)
{
   Console.WriteLine($"StrWithInt: {it.StrWithInt}");
}
Console.ReadLine();

我得到这样的结果。

StrWithInt: 340189285
StrWithInt: 340189285
StrWithInt: 340189285

所有值都相同。但我希望看到这个 属性 的不同值。
我怎样才能到达它?

With(...) 方法有许多重载,您可以在其中找到以下重载:

IPostprocessComposer<T> With<TProperty>(
      Expression<Func<T, TProperty>> propertyPicker,
      Func<TProperty> valueFactory);

所以你可以通过传递随机数工厂来使用这个,之后结果总是不同的:

fixture.Customize<A.NestedA>(ob =>
    ob.With(p => p.StrWithInt, () => r.Next().ToString())
);

在您的情况下,您选择静态的,它始终将相同的值分配给指定的 属性。