开发者

How to create an IList of anonymous classes using AutoFixture

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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜