如何使用 AutoFixture 创建匿名类的 IList
我之前在此链接上发布了一个问题:
我需要能够执行相同的操作,但对于嵌套类:
像这样:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
AutoFixture 的 AutoProperties 功能仅将值分配给可写属性。
ParentClass.Children
未填充的原因是它是只读属性 - AutoFixture 不会尝试分配值,因为它知道这是不可能的。但是,假设您已经有一个 ParentClass 实例,您可以要求 AutoFixture 为您填充该集合:
这可以封装到如下自定义中:
由于
Children
是一个IList;
您还需要为此提供映射,除非您使用 MultipleCustomization:这绝对是我们考虑添加到 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:
This can be encapsulated into a customization like this:
Since
Children
is anIList<ChildClass>
you'll also need to provide a mapping for that unless you use the MultipleCustomization: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.