gpt4 book ai didi

c# - 如何使用 AutoFixture 创建匿名类的 IList

转载 作者:太空狗 更新时间:2023-10-30 01:26:10 26 4
gpt4 key购买 nike

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

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。

最佳答案

AutoFixture 的 AutoProperties 功能只为可写属性赋值。为什么ParentClass.Children未被填充是因为它是只读属性 - AutoFixture 不会尝试分配值,因为它知道这是不可能的。

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

fixture.AddManyto(parentClass.Children);

这可以封装成这样的定制:

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

Children是一个 IList<ChildClass>您还需要为此提供一个映射,除非您使用 MultipleCustomization :

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

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

关于c# - 如何使用 AutoFixture 创建匿名类的 IList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5500654/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com