【问题标题】:How to generate a stub object of an arbitrary Type not known at compile time using AutoFixture如何使用 AutoFixture 生成编译时未知的任意类型的存根对象
【发布时间】:2013-09-23 07:20:28
【问题描述】:

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

Type type = paramInfo.ParameterType;

现在我想从这个类型创建存根对象。有可能吗?我尝试使用自动固定装置:

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 吗?在反射 (Type) 和泛型 (&lt;T&gt;) 之间切换......有点痛苦(而且速度很慢) - 你可以它(还有更多反射) - 但最好避免如果尽可能...
  • 似乎 AutoFixture 没有为这个问题提供简单的解决方案:thomasardal.com/…
  • 是否可以用 Type 创建存根? (带或不带自动夹具)
  • Enrico Campidoglio 提供的答案是正确的,但您为什么要首先这样做呢?听起来您正在尝试自动化 AutoFixture 的使用(这很好),但可能有更好更好、更惯用的方法......
  • 您可以轻松地将 AutoFixture 变成一个自动模拟容器。参见例如这个答案的概述:stackoverflow.com/a/12871065/126014

标签: c# unit-testing autofixture


【解决方案1】:

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);

【讨论】:

    猜你喜欢
    • 2017-08-08
    • 1970-01-01
    • 1970-01-01
    • 2010-11-11
    • 2022-08-11
    • 2016-01-17
    • 2021-12-07
    • 2013-05-17
    • 1970-01-01
    相关资源
    最近更新 更多