What does CreateMany with seed do?
Asked Answered
C

1

9

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

Cirrostratus answered 11/2, 2015 at 19:32 Comment(0)
M
16

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".

Monahon answered 12/2, 2015 at 11:12 Comment(1)
+1 FWIW, we're considering (re)moving the seed overloads in AutoFixture version 4 github.com/AutoFixture/AutoFixture/issues/151Sarsenet

© 2022 - 2024 — McMap. All rights reserved.