如何使用AutoFixture生成编译时未知的任意类型的存根对象

use*_*794 6 c# unit-testing autofixture

我可以得到像这样的构造函数参数类型:

Type type = paramInfo.ParameterType;
Run Code Online (Sandbox Code Playgroud)

现在我想从这种类型创建存根对象.有可能吗?我试过autofixture:

public TObject Stub<TObject>()
{
   Fixture fixture = new Fixture();   
   return fixture.Create<TObject>();
}
Run Code Online (Sandbox Code Playgroud)

..但它不起作用:

Type type = parameterInfo.ParameterType;   
var obj = Stub<type>();//Compile error! ("cannot resolve symbol type")
Run Code Online (Sandbox Code Playgroud)

你能救我吗?

Enr*_*lio 11

AutoFixture 确实有一个非泛型的API来创建对象,虽然有点隐藏(按设计):

var fixture = new Fixture();
var obj = new SpecimenContext(fixture).Resolve(type);
Run Code Online (Sandbox Code Playgroud)

由@meilke链接的博客文章指出,如果您经常发现自己需要这个,可以将其封装在扩展方法中:

public object Create(this ISpecimenBuilder builder, Type type)
{
    return new SpecimenContext(builder).Resolve(type);
}
Run Code Online (Sandbox Code Playgroud)

这可以让你简单地做:

var obj = fixture.Create(type);
Run Code Online (Sandbox Code Playgroud)