Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 970
user2598794 Avatar asked Sep 23 '13 07:09

user2598794


1 Answers

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);
like image 110
Enrico Campidoglio Avatar answered Nov 15 '22 09:11

Enrico Campidoglio