我可以像这样获取构造函数参数的类型:
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 确实有一个非通用的 API 来创建对象,albeit kind of hidden (by design) :
var fixture = new Fixture();
var obj = new SpecimenContext(fixture).Resolve(type);
作为blog post @meilke 链接指出,如果您发现自己经常需要它,您可以将它封装在扩展方法中:
public object Create(this ISpecimenBuilder builder, Type type)
{
return new SpecimenContext(builder).Resolve(type);
}
它允许您简单地做:
var obj = fixture.Create(type);
关于c# - 如何使用 AutoFixture 生成编译时未知的任意类型的 stub 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18953714/