Reputation: 2617
I know I can use AutoFixture to create an auto-mocked instance using
var person = fixture.Create<Person>();
But, if I want to customise the way a Person
is created I have several options. One is to use Build
var person = fixture.Build<Person>()
.With(x => x.FirstName, "Owain")
.Create();
And another is to use Customize
fixture.Customize<Person>(c => c.With(x => x.FirstName, "Owain"));
var person = fixture.Create<Person>();
So, my question is, what are the various merits and pitfalls of each approach listed above, and are there any other / better approaches?
Upvotes: 10
Views: 5002
Reputation: 1828
.Build<>.With().Create()
creates the instance with those properties. Future calls to .Create<>()
(for the same type) are unnafected.
.Customize<>
defines extra "steps" for the creation of a type. This means that all future calls to .Create<>()
(for the same type) will go through the same steps.
Basically, you would use customize for cases where all created objects of a specific type require the same set-up.
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"
Relevant pages of the holy book:
Upvotes: 6