Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does CreateMany with seed do?

What does the CreateMany overload with the T seed parameter actually do? I've tried to seed, but the seed seems to have no effect on the created objects. For example, I was expecting that if my seed had a property of type string, that either:

  • the string value would be used to populate that property in all newly created objects

  • or the string value would be used as a prefix when setting that property in all newly created objects

like image 333
SFun28 Avatar asked Feb 11 '15 19:02

SFun28


1 Answers

tl;dr

As a general rule, AutoFixture does not guarantee how seed values are going to be used during the creation process, if at all. This characteristic stems from the way AutoFixture is designed.

Background

Every time AutoFixture is asked to create an object of a certain Type, the request is routed through a pipeline of objects called "builders". Each builder is responsible for handling a certain kind of request (whether it be a request for a concrete type, an interface, a property, a field etc). If a builder encounters a request it can handle, it's going to return a value for it and the pipeline restarts with the next request.

Given the above, if you want to create an object based on a seed, all AutoFixture can do is make sure that the seed value you provide is embedded in the request that is sent through the pipeline. Then it's up to the builders to decide what to do with that value.

Solution

AutoFixture currently comes with a single builder that takes into account seed values and that's the one for strings.

However, you can tell AutoFixture how it should use seed values when creating objects of any type by customizing a Fixture specifically for that type with the FromSeed method:

var fixture = new Fixture();
fixture.Customize<Foo>(c =>
    c.FromSeed(seed =>
        {
            // return an instance of Foo
            // that uses the seed value in some way
        }));

The factory function you provide to FromSeed will be invoked every time AutoFixture has to create an instance of Foo and it will be passed the seed value from the Fixture. For example, given this:

fixture.CreateMany<Foo>(seed: new Foo { Bar = "baz" });

the seed parameter of the factory function will receive the Foo seed object that has the Bar property set to "baz".

like image 94
Enrico Campidoglio Avatar answered Nov 16 '22 16:11

Enrico Campidoglio