c# – 如何使用AutoFixture生成编译时未知的任意类型的存根对象
发布时间:2020-12-15 04:28:27 所属栏目:百科 来源:网络整理
导读:我可以得到像这样的构造函数参数类型: Type type = paramInfo.ParameterType; 现在我想从这种类型创建存根对象.有可能吗?我试过autofixture: public TObject StubTObject(){ Fixture fixture = new Fixture(); return fixture.CreateTObject();} ..但它不
我可以得到像这样的构造函数参数类型:
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); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |