Go read
- Nikos Baxevanis's blog
- Enrico Camidoglio's blog
- Mark Seemann's AutoFixture posts (Encapsulating AutoFixture Customizations is the best)
for great examples of customizations and how to package, mix and mingle them.
Main principle is that you make your Customizations as granular as possible.
Then, you need to feed them in to the processing pipeline via either:
AutoData
-derived attributes for global stuff (i.e. likeMyTestConventions
in Mark's answer )- A
CustomizeWith
helper[1] or similar - Trickery such as doing a
[Freeze( As ... )]
My implementation
Automating this, I'd write:
[Theory, AutoData]
public static void OutOfBandCustomization(
[CustomizeWith( typeof( MyFakerCustomization ) )] MyClass sut )
{
}
Using this customization:
public class MyFakerCustomization : ICustomization
{
void ICustomization.Customize( IFixture fixture )
{
var knownText = "This text is not anonymous";
fixture.Register<int, IMyInterface>( i =>
new FakeMyInterface( i, knownText ) );
}
}
Obviously registering a string
and/or using AutoMoqCustomization
might also be useful.
My general helpers
[1] CustomizeWith
is this helper Attribute (hat tip to Adam Jasinski):
[AttributeUsage( AttributeTargets.Parameter, AllowMultiple = true )]
sealed class CustomizeWithAttribute : CustomizeAttribute
{
readonly Type _type;
public CustomizeWithAttribute( Type customizationType )
{
if ( customizationType == null )
throw new ArgumentNullException( "customizationType" );
if ( !typeof( ICustomization ).IsAssignableFrom( customizationType ) )
throw new ArgumentException(
"Type needs to implement ICustomization" );
_type = customizationType;
}
public override ICustomization GetCustomization( ParameterInfo parameter )
{
return (ICustomization)Activator.CreateInstance( _type );
}
}
Aside
One tip: you can express
fixture.Register<int, IMyInterface>( i =>
new FakeMyInterface( i, knownText ) );
as
fixture.Customize<IMyInterface>(c =>c.FromFactory((int i)=>
new FakeMyInterface(i,knownText)));
too. While this doesn't make your case easier, it is a more general way of customizing what's going on.
Internally, Register
is [currently]:
fixture.Customize<T>(c => c.FromFactory(creator).OmitAutoProperties());