4

使用autofixture,我试图构建匿名实例Project

 _f=new Fixture().Customize(new AutoMoqCustomization());
 _p=_f.CreateAnonymous<Project>();

这失败了,导致Project公共构造函数要求IList<Partner>

public Project(/*.....*/,IList<Partner> partners){
  Guard.AgainstEmpty(partners);
}

堆栈跟踪没有意义(至少 - 对我来说)。只是一些反射yada-yada:

失败:System.Reflection.TargetInvocationException :调用的目标已引发异常。
---- System.ArgumentException : 值不在预期范围内。
在 System.RuntimeMethodHandle._InvokeConstructor(IRuntimeMethodInfo 方法,Object[] args,SignatureStruct& 签名,RuntimeType declaringType)

那么 - 如何确保 autoFixture 传递匿名的合作伙伴集合以构建它?


这不是 的错IList<Partners>。还有一个参数叫做Priority. Priority本身在构造函数中持有MeasureMeasure持有IList<Indicator>和调用Guard.AgainstEmpty(indicators)

所以它看起来像这样:

fixture.CreateAnonymous<Foo>(); //kaboom!
public class Foo{
  public Foo(IList<Bar> bars){
    Guard.AgainstEmpty(bars); //just checks count for ienumerable & throws if 0
    Bars=bars;
  }
  public IList<Bar> Bars {get;private set;} //should be readonly collection...
}

public class Fizz{
  public Fizz(Foo foo){
    Foo=foo;
  }
  public Foo{get;private set;}
}

public class Bar{}

施工方法失败Guard.AgainstEmpty。所以 - 问题变成了 - 如何确保 AutoFixture 在构建 foos 之前填充条形集合中的一些条形?

4

1 回答 1

1

这有帮助。浏览源代码通常会有所帮助。

var indicators=_f.CreateMany<Indicator>();
_f.Register<IList<Indicator>>(()=>indicators.ToList());

不过可能有更好的方法。


总的来说,这就是它目前的样子:

  _f=new Fixture().Customize(new AutoMoqCustomization());
  var indicators=_f.CreateMany<Indicator>();
  _f.Register<IList<Indicator>>(()=>indicators.ToList());
  var regionName=_f.CreateAnonymous<string>();
  _f.Register<string,Country,bool,Region>((name,country,call)=>
    new Region(regionName,_f.CreateAnonymous<Country>(),true));
  _c.Set(x=>x.Regions,_f.CreateMany<Region>().ToList());
  _f.Register<IList<ManagementBoardEntry>>(()=>
    _f.CreateMany<ManagementBoardEntry>().ToList());
  _f.Register<IList<FinancialInfoEntry>>(()=>
    _f.CreateMany<FinancialInfoEntry>().ToList());
  _f.Register<IList<Partner>>(()=>_f.CreateMany<Partner>().ToList());
  _p=_f.CreateAnonymous<Project>();

不能称之为美丽(欢迎任何重构建议),但它仍然比手动编写所有内容要好得多。


使用IListthere 肯定是错误的选择。更糟糕的是 - 我IList也在使用属性。这邀请客户直接使用它们,而不是通过聚合根。

使用时有一个缺点params。不能使用多个(除非我又错过了一些基础知识)。而且我正在接收列表作为输入(excel 表 DOM 的一部分),不知道编译时间会有多少元素。

模型真的很新鲜。刚烤好(所以我很有可能对那些空虚检查有误,将与客户和业务分析师讨论)。

我的策略是自由地雕刻它并通过单元测试将其推向所需的状态。这是我有点不喜欢严格的 TDD 的实际原因。它窃取了焦点,迫使我过早地考虑细节而不是整个画面。我更喜欢画草图并细化,直到它看起来不错。但这可能是因为我对测试不够流利。

无论如何 - 谢谢你的好建议。我将继续了解有关 AutoFixture 的更多信息。

于 2010-09-09T14:04:53.660 回答