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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With