Until now, I've shown you how you can make wholesale adjustments or customizations to an entire Fixture instance, effectively changing the way it creates all instances of a particular type.

In some scenarios, you'd rather want to customize how a single instance is created without influencing other instances of the same type. For this purpose, AutoFixture includes a class called ObjectBuilder<T> that can be used to do exactly that.

The easiest way to get an instance of this class is by calling Build on a Fixture instance. This will give you an instance of ObjectBuilder<T> that you can use to customize the build steps. When you are done, CreateAnonymous returns the built instance.

var mc = fixture.Build<MyClass>().CreateAnonymous();

This particular example doesn't define any customizations, so it's equivalent to

var mc = fixture.CreateAnonymous<MyClass>();

In fact, Fixture.CreateAnonymous is little more than a convenience method wrapping an ObjectBuilder (there's a few extra differences, but that's a topic for another post).

It's worth noting that the object specified by the type parameter to the Build method is first created when you call CreateAnonymous.

In future posts I'll demonstrate how to use the Build method to customize individual anonymous variables.



Wish to comment?

You can add a comment to this post by sending me a pull request. Alternatively, you can discuss this post on Twitter or somewhere else with a permalink. Ping me with the link, and I may respond.

Published

Tuesday, 26 May 2009 21:30:35 UTC

Tags



"Our team wholeheartedly endorses Mark. His expert service provides tremendous value."
Hire me!
Published: Tuesday, 26 May 2009 21:30:35 UTC