Extending AutoFixture
AutoFixture supports three main categories of extension points
Specimen builders
Behaviors
Customizations
Specimen builders
Specimen builders are components that can be used to customize the creation of objects that AutoFixture can't handle with the default setup.
A specimen builder must implement the ISpecimenBuilder
interface that looks like the following snippet
A request can be virtually of any type but most commonly they are reflection types like Type
, PropertyInfo
, ParameterInfo
and so on. The AutoFixture kernel uses a chain of responsibility to explore all the available builders and stop when a builder able to satisfy the request is met, directly or indirectly.
The context parameter represents the context in which the request is being handled. It's interface exposes only the Resolve
method that is used to invoke AutoFixture's chain of responsibility to generate a value.
Here is an example of a specimen builder used to create instances of a specific type.
Specimen builder are added to a given fixture via its Customizations collection.
Behaviors
Together with specimen builders, behaviors are part of the graph used to represent the chain of responsibility used to create values.
Unlike the specimen builders, that can be seen as the leaves of the graph and therefore can only respond to a request, behaviors have access to both the request and the response and can act or modify them.
For example, the TracingBehavior
, which is included in the AutoFixture core package, can be used to track the chain of calls used to serve a certain request.
When executing the snippet above, the following will be printed on the standard out
Behaviors implement the ISpecimenBuilderTransformation
interface. This is what the interface looks like
Customizations
Finally, AutoFixture uses classes implementing the ICustomization
interface to wrap in a single place multiple changes to the fixture configuration.
The ICustomization
interface exposes a single method, Customize
, that accepts a fixture and applies configuration changes to it.
For example, the customization below injects values for int
and string
.
The customization can then be used as it follows.
In the snippet above you can see how AutoFixture uses the injected values together with the ones specified in the customization when constructing an instance of SampleValueObject
.
Last updated