【问题标题】:AutoFixure Fixture.Build().With() with different valuesAutoFixture Fixture.Build().With() 具有不同的值
【发布时间】:2019-05-31 18:08:23
【问题描述】:

考虑一个类

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 的类属性 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

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

【问题讨论】:

    标签: c# autofixture


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢尼基塔。结果比我想象的要容易得多。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-13
    • 1970-01-01
    • 2013-03-04
    相关资源
    最近更新 更多