【问题标题】:How to create an IList of anonymous classes using AutoFixture如何使用 AutoFixture 创建匿名类的 IList
【发布时间】:2011-03-31 13:30:34
【问题描述】:

我之前在此链接上发布了一个问题:

Class with a nested collection - how do I populate the nested class?

我需要能够做同样的事情,但使用嵌套类:

像这样:

public class ParentClass
{
   public int Value;
   public IList<ChildClass> Children;
}

public class ChildClass
{
   etc...
}

我试过了:

Fixture.Register(()=>Fixture.CreateMany<ChildClass>();

但这不起作用,有什么想法吗? 我正在使用 AutoFixture 2.0。

【问题讨论】:

    标签: c# autofixture


    【解决方案1】:

    AutoFixture 的 AutoProperties 功能仅将值分配给可写属性。 ParentClass.Children 没有被填充的原因是因为它是一个只读属性 - AutoFixture 不会尝试分配值,因为它知道这是不可能的。

    但是,假设您已经有一个 ParentClass 的实例,您可以让 AutoFixture 为您填充集合:

    fixture.AddManyto(parentClass.Children);
    

    这可以封装成这样的自定义:

    fixture.Customize<ParentClass>(c => c.Do(pc => fixture.AddManyTo(pc.Children)));
    

    由于ChildrenIList&lt;ChildClass&gt;,您还需要为此提供映射,除非您使用MultipleCustomization

    fixture.Register<IList<ChildClass>>(() => fixture.CreateMany<ChildClass>().ToList());
    

    这绝对是我们considered adding to the MultipleCustomization, but decided to postpone until after release 2.1 的一种行为,因为事实证明它并不完全容易实现。

    【讨论】:

    • 非常感谢!尽管自定义对我不起作用,但我设法使该工作正常进行。我只使用了 register 方法。
    • 好的,很好-我不得不承认我将上面的代码直接写到了我的答案中,所以在某处可能会有一点错误......但总体思路是正确的:)
    猜你喜欢
    • 2013-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-20
    • 1970-01-01
    • 2011-04-13
    相关资源
    最近更新 更多