A non-generic AutoFixture Create method

October 24, 2016 @ 8:03 am Posted to .Net by Antony Koch

Sometimes I need to dynamically generate test fixtures, but don’t in the test context have the ability to use generics, instead having only an instance of a Type.

I looked through the AutoFixture code and managed to find a reflection-friendly way to return me an object that can then be changed using Convert.ChangeType where necessary. Here’s the snippet:


typeof(SpecimenFactory).GetMethods().Single(x => x.IsStatic && x.IsGenericMethod && x.Name == "Create" && x.GetParameters().Length == 1 && x.GetParameters().Single().ParameterType == typeof(ISpecimenBuilder)).MakeGenericMethod(type).Invoke(fixture, new [] { fixture });

Leave a Reply

Your email address will not be published. Required fields are marked *