我可以这样获取构造函数参数的类型:
Type type = paramInfo.ParameterType;
现在,我想从这种类型创建 stub 对象。有可能吗?我尝试使用自动治具:
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确实具有用于创建对象albeit kind of hidden (by design)的非通用API:
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);