Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
987 views
in Technique[技术] by (71.8m points)

c# - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...