How to generate a stub object of an arbitrary Type not known at compile time using AutoFixture

StackOverflow https://stackoverflow.com/questions/18953714

  •  29-06-2022
  •  | 
  •  

Question

I can get type of constructor parameter like this:

Type type = paramInfo.ParameterType;

Now I want to create stub object from this type. Is is possible? I tried with autofixture:

public TObject Stub<TObject>()
{
   Fixture fixture = new Fixture();   
   return fixture.Create<TObject>();
}

.. but it doesn't work:

Type type = parameterInfo.ParameterType;   
var obj = Stub<type>();//Compile error! ("cannot resolve symbol type")

Could you help me out?

Was it helpful?

Solution

AutoFixture does have a non-generic API to create objects, albeit kind of hidden (by design):

var fixture = new Fixture();
var obj = new SpecimenContext(fixture).Resolve(type);

As the blog post linked by @meilke points out, if you find yourself needing this often, you can encapsulate it in an extension method:

public object Create(this ISpecimenBuilder builder, Type type)
{
    return new SpecimenContext(builder).Resolve(type);
}

which allows you to simply do:

var obj = fixture.Create(type);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top