【问题标题】:AutoFixture Customize vs BuildAutoFixture 自定义与构建
【发布时间】:2019-08-16 14:18:54
【问题描述】:

我知道我可以使用 AutoFixture 创建一个自动模拟实例

var person = fixture.Create<Person>();

但是,如果我想自定义 Person 的创建方式,我有几个选择。一种是使用Build

var person = fixture.Build<Person>()
                    .With(x => x.FirstName, "Owain")
                    .Create();

还有一个是使用Customize

fixture.Customize<Person>(c => c.With(x => x.FirstName, "Owain"));
var person = fixture.Create<Person>();

所以,我的问题是,上面列出的每种方法的各种优点和缺陷是什么,还有其他/更好的方法吗?

【问题讨论】:

    标签: c# autofixture


    【解决方案1】:

    .Build&lt;&gt;.With().Create() 使用这些属性创建实例。未来对.Create&lt;&gt;()(相同类型)的调用不会受到影响。

    .Customize&lt;&gt; 为创建类型定义了额外的“步骤”。这意味着将来对.Create&lt;&gt;()(针对同一类型)的所有调用都将执行相同的步骤。

    基本上,您可以在所有创建的特定类型的对象都需要相同设置的情况下使用自定义。


    var person_1 = fixture.Build<Person>()
        .With(x => x.FirstName, "Owain")
        .Create();
    
    var person_2 = fixture.Create<Person>();
    
    fixture.Customize<Person>(c => c.With(x => x.FirstName, "Owain"));
    // All subsequent calls to Create for type Person will use the customization.
    
    var person_3 = fixture.Create<Person>();
    var person_4 = fixture.Create<Person>();
    
    //person_1.FirstName == "Owain"
    //person_2.FirstName != "Owain"
    //person_3.FirstName == "Owain"
    //person_4.FirstName == "Owain"
    

    圣书的相关页面:

    1. 自定义:Customizing A Type's Builder With AutoFixture
    2. Build.Do.With:Do Redux

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多