c# - 如何使用 AutoFixture 生成编译时未知的任意类型的 stub 对象

标签 c# unit-testing autofixture

我可以像这样获取构造函数参数的类型:

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/

相关文章:

c# - AutoFixture,从预定义列表中随机选择

c# - 如何使用 C# 应用程序获取图像标签

c# - 基本类型转换 (c#)

unit-testing - 库中的实用程序测试类应该接受测试还是主要测试?

c# - 最小起订量 - 无论使用的参数如何,都执行带有参数的验证方法

.net - 自动夹具自动数据错误 - 未提供参数

c# - AutoFixture 能否从提供的数据集中生成随机字符串/文本?

c# - 如何选择多个文件夹

c# - 禁用动态图像按钮的回发

asp.net - 测试: I *want* to test web.配置