如何生成任意类型的存根对象不使用AutoFixture在编译时已知 [英] How to generate a stub object of an arbitrary Type not known at compile time using AutoFixture
本文介绍了如何生成任意类型的存根对象不使用AutoFixture在编译时已知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我能得到这样的构造函数参数的类型:
I can get type of constructor parameter like this:
Type type = paramInfo.ParameterType;
现在我想从这种类型的创建存根对象。是有可能吗?我试着用autofixture:
Now I want to create stub object from this type. Is is possible? I tried with autofixture:
public TObject Stub<TObject>()
{
Fixture fixture = new Fixture();
return fixture.Create<TObject>();
}
..但它不工作:
.. but it doesn't work:
Type type = parameterInfo.ParameterType;
var obj = Stub<type>();//Compile error! ("cannot resolve symbol type")
你能帮我吗?
Could you help me out?
推荐答案
AutoFixture的确实的有一个非通用API来创建对象,的尽管那种隐藏的(设计):
AutoFixture does have a non-generic API to create objects, albeit kind of hidden (by design):
var fixture = new Fixture();
var obj = new SpecimenContext(fixture).Resolve(type);
作为的由@meilke链接博客帖子指出,如果你发现自己需要这通常,你可以在一个扩展方法封装它:
As the blog post linked by @meilke points out, if you find yourself needing this often, you can encapsulate it in an extension method:
public object Create(this ISpecimenBuilder builder, Type type)
{
return new SpecimenContext(builder).Resolve(type);
}
允许你简单地做:
which allows you to simply do:
var obj = fixture.Create(type);
这篇关于如何生成任意类型的存根对象不使用AutoFixture在编译时已知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文