首页 > 解决方案 > AutoFixure Fixture.Build().With() 具有不同的值

问题描述

考虑一个类

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框架来生成A具有随机内容的类实例。
NestedA类属性StrWithInt是一个string类型,但它的值必须是一个数字,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

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

标签: c#autofixture

解决方案


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

在您的情况下,您选择静态的,它总是为指定的属性分配相同的值。


推荐阅读