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

发布于 2024-10-28 03:31:00 字数 529 浏览 3 评论 0原文

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

具有嵌套集合的类 - 如何填充嵌套类?

我需要能够执行相同的操作,但对于嵌套类:

像这样:

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

public class ChildClass
{
   etc...
}

我尝试了这个:

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

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

I previously posted a question on this link:

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

I need to be able to do the same but with nested classes:

like so:

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

public class ChildClass
{
   etc...
}

I tried this:

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

But this isn't working, any ideas?
I'm using AutoFixture 2.0.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

末骤雨初歇 2024-11-04 03:31:00

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

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

fixture.AddManyto(parentClass.Children);

这可以封装到如下自定义中:

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

由于 Children 是一个 IList; 您还需要为此提供映射,除非您使用 MultipleCustomization

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

这绝对是我们考虑添加到 MultipleCustomization 中的行为,但决定推迟到在版本 2.1 之后,因为事实证明它并不完全容易实现。

The AutoProperties features of AutoFixture only assigns values to writable properties. The reason why ParentClass.Children isn't being populated is because it's a read-only property - AutoFixture doesn't attempt to assign a value because it knows that this is impossible.

However, assuming that you already have an instance of ParentClass, you can ask AutoFixture to fill the collection for you:

fixture.AddManyto(parentClass.Children);

This can be encapsulated into a customization like this:

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

Since Children is an IList<ChildClass> you'll also need to provide a mapping for that unless you use the MultipleCustomization:

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

This is definitely a behavior that we considered adding to the MultipleCustomization, but decided to postpone until after release 2.1 because it turns out to be not entirely easy to implement.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文