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

我可以得到像这样的构造函数参数类型:
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);

相关文章

原文地址:http://msdn.microsoft.com/en-us/magazine/cc163...
前言 随着近些年微服务的流行,有越来越多的开发者和团队所采...
最近因为比较忙,好久没有写博客了,这篇主要给大家分享一下...
在多核CPU在今天和不久的将来,计算机将拥有更多的内核,Mic...
c语言输入成绩怎么判断等级
字符型数据在内存中的存储形式是什么