How to create an IList of anonymous classes using AutoFixture

Earlier I asked a question at this link:

A class with a nested collection - how can I populate a nested class?

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

So:

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

I tried this:

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

But that doesn't work, any ideas? I am using AutoFixture 2.0.

+4
source share
1 answer

AutoProperties AutoFixture properties are assigned values ​​only for writable properties. The reason ParentClass.Children not populated is because it is a read-only property. - AutoFixture does not try to assign a value because it knows that this is not possible.

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

 fixture.AddManyto(parentClass.Children); 

This can be encapsulated in a setting like this:

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

Since Children is an IList<ChildClass> , you also need to provide a mapping if you are not using MultipleCustomization :

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

This is definitely the behavior that we considered an addition to MultipleCustomization, but decided to postpone to version 2.1 , because it is not so completely simple to implement.

+4
source

Source: https://habr.com/ru/post/1346055/


All Articles