This project is read-only.

Using Fixture.Build with Fixture.Customize

Jun 28, 2011 at 10:44 AM


When i use Fixture.Build to create my objects, AutoFixture ignores my customizations. Why is this?

Fixture.Customize<User>(x => x.Without(u => u.Id));
Fixture.CreateAnonymous<User>(); // Will have empty id
Fixture.Build<User>().CreateAnonymous(); // Will have set id

Seems like a bug, or am i missing the point? :-)


Jun 28, 2011 at 9:46 PM

This behavior is by design. The Build<T> method is essentially a one-off Customization, so it ignores any previous Customizations and does only exactly what you tell it.

Jun 29, 2011 at 7:28 AM

Okay, that makes sence, since not having a "build without customizations" feature would be bad :-)
Would it not make sence though, having a Build<T>().WithCustomizations() method?

My problem is that in my domain, i have some different types of documents, all which have an Id, which RavenDB will eventually set.
We use integration test of our application services, and therefor, each time i create a new root document, i always have to do Without(x => x.Id), to ensure the id is empty so it can be set by RavenDB:

fixture.Build<User>().FromFactory(() => new User(company)).Without(x => x.Id).CreateAnonymous();

fixture.Build<Case>().FromFactory(() => Case.Create(user)).Without(x => x.Id).CreateAnonymous();

I need to use Build<T>, since a have to use FromFactory (i want to control which users are in each company, and which cases are attached to each user).
Can i avoid using FromFactory() in this case?

I can of course, just make a method (e.g. an extension method to Fixture) which does the above. I was just curious if theres a better way. :-)

Jun 29, 2011 at 10:27 PM

Would it be possible for you to invert your setup so that you simply build a standard User and then afterwards reference which company they belong to? That would make things much easier.

Otherwise, perhaps you can Freeze (and unfreeze) the company before you create the User... See e.g. this discussion thread.