Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoFixture Customize vs Build

Tags:

c#

autofixture

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?

like image 275
Owain Williams Avatar asked Aug 16 '19 14:08

Owain Williams


1 Answers

.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:

  1. Customize: Customizing A Type's Builder With AutoFixture
  2. Build.Do.With: Do Redux
like image 81
IOrlandoni Avatar answered Oct 13 '22 00:10

IOrlandoni