我可以得到像这样的构造函数参数类型:
Type type = paramInfo.ParameterType;
现在我想从这种类型创建存根对象.有可能吗?我试过autofixture:
public TObject Stub<TObject>() { Fixture fixture = new Fixture(); return fixture.Create<TObject>(); }
..但它不起作用:
Type type = parameterInfo.ParameterType; var obj = Stub<type>();//Compile error! ("cannot resolve symbol type")
你能救我吗?
解决方法
AutoFixture确实有一个非泛型API来创建对象,albeit kind of hidden (by design):
var fixture = new Fixture(); var obj = new SpecimenContext(fixture).Resolve(type);
由@meilke链接的blog post指出,如果你经常发现自己需要这个,你可以将它封装在扩展方法中:
public object Create(this ISpecimenBuilder builder,Type type) { return new SpecimenContext(builder).Resolve(type); }
这可以让你简单地做:
var obj = fixture.Create(type);