AutoFixture 自定义与构建
AutoFixture Customize vs Build
我知道我可以使用 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>();
所以,我的问题是,上面列出的每种方法的各种优点和缺陷是什么,还有其他/更好的方法吗?
.Build<>.With().Create()
创建具有这些属性的实例。未来对 .Create<>()
的调用(对于同一类型)不会受到影响。
.Customize<>
为类型的创建定义额外的 "steps"。这意味着以后对 .Create<>()
的所有调用(对于同一类型)都将经过相同的步骤。
基本上,如果特定类型的所有已创建对象都需要相同的设置,您将使用自定义。
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"
圣书相关页数:
- 自定义:Customizing A Type's Builder With AutoFixture
- Build.Do.With: Do Redux
我知道我可以使用 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>();
所以,我的问题是,上面列出的每种方法的各种优点和缺陷是什么,还有其他/更好的方法吗?
.Build<>.With().Create()
创建具有这些属性的实例。未来对 .Create<>()
的调用(对于同一类型)不会受到影响。
.Customize<>
为类型的创建定义额外的 "steps"。这意味着以后对 .Create<>()
的所有调用(对于同一类型)都将经过相同的步骤。
基本上,如果特定类型的所有已创建对象都需要相同的设置,您将使用自定义。
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"
圣书相关页数:
- 自定义:Customizing A Type's Builder With AutoFixture
- Build.Do.With: Do Redux