Last active
September 11, 2020 08:00
-
-
Save bartelink/3151233 to your computer and use it in GitHub Desktop.
AutoFixture customization to allow insertion of arbitrary postprocessing logic a la Customize( c=>c.Do()) but in a global manner
Revised for v3 (initally for v2)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace Ploeh.AutoFixture | |
{ | |
using Kernel; | |
using System; | |
public class PostProcessWhereIsACustomization<T> : ICustomization | |
where T : class | |
{ | |
readonly PostProcessSpecimensBehavior _behavior; | |
public PostProcessWhereIsACustomization( Action<T> action ) | |
{ | |
_behavior = new PostProcessSpecimensBehavior( action ); | |
} | |
void ICustomization.Customize( IFixture fixture ) | |
{ | |
fixture.Behaviors.Add( _behavior ); | |
} | |
class PostProcessSpecimensBehavior : ISpecimenBuilderTransformation | |
{ | |
readonly Action<object> _applyActionIfSpecimenIsOfTypeT; | |
public PostProcessSpecimensBehavior( Action<T> action ) | |
{ | |
_applyActionIfSpecimenIsOfTypeT = x => | |
{ | |
var asT = x as T; | |
if ( asT != null ) | |
action( asT ); | |
}; | |
} | |
ISpecimenBuilder ISpecimenBuilderTransformation.Transform( ISpecimenBuilder builder ) | |
{ | |
return new SpecimenBuilderPostProcessor( builder, _applyActionIfSpecimenIsOfTypeT ); | |
} | |
class SpecimenBuilderPostProcessor : ISpecimenBuilderNode | |
{ | |
readonly ISpecimenBuilder _builder; | |
readonly Action<object> _postProcess; | |
public SpecimenBuilderPostProcessor( ISpecimenBuilder builder, Action<object> initializationAction ) | |
{ | |
_postProcess = initializationAction; | |
_builder = builder; | |
} | |
object ISpecimenBuilder.Create( object request, ISpecimenContext context ) | |
{ | |
var specimen = _builder.Create( request, context ); | |
_postProcess( specimen ); | |
return specimen; | |
} | |
ISpecimenBuilderNode ISpecimenBuilderNode.Compose( System.Collections.Generic.IEnumerable<ISpecimenBuilder> builders ) | |
{ | |
return new SpecimenBuilderPostProcessor( new CompositeSpecimenBuilder( builders ), _postProcess ); | |
} | |
System.Collections.Generic.IEnumerator<ISpecimenBuilder> System.Collections.Generic.IEnumerable<ISpecimenBuilder>.GetEnumerator() | |
{ | |
yield return _builder; | |
} | |
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() | |
{ | |
yield return _builder; | |
} | |
} | |
} | |
} | |
} |
I've spent last two days digging through the google and trying to debug unit tests that was using my own customization class, that didn't work. Thankfully here I've found one that works beautifully. Thanks for sharing.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example consumption: