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

五迷三道 提交于 2019-12-23 09:27:27

问题


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?


回答1:


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);


来源:https://stackoverflow.com/questions/18953714/how-to-generate-a-stub-object-of-an-arbitrary-type-not-known-at-compile-time-usi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!