Setting one property based on another in AutoFixture
Asked Answered
A

1

5

I am trying to create a fixture using AutoFixture where one property of the object is related to another, and one of the properties is created as part of the fixture.

What I have so far is:

fixture = new Fixture().Customize(new MultipleCustomization());
Object object;
double constant;
object = fixture.Build<Object>()
                .With(o => o.PropertyOne, fixture.Create<double>)
                .With(o => o.PropertyTwo, constant * o.PropertyOne)
                .Create());

Which doesn't work because "The name 'o' does not exist in the current context", which makes sense.

Is there any way to do this as part of the creation of the fixture?

My situation is a little more complicated because I am actually generating a list, so the code would look like:

fixture = new Fixture().Customize(new MultipleCustomization());
List<Object> objectListFixture;
double constant;
objectListFixture.AddRange(
    fixture.Build<Object>()
           .With(o => o.PropertyOne, fixture.Create<double>)
           .With(o => o.PropertyTwo, constant * o.PropertyOne)
           .CreateMany());

And I would really like to avoid a for loop if possible.

Arboretum answered 12/7, 2017 at 15:26 Comment(6)
What do you mean by 'the same double is created for each member of the list'?Acrilan
The double created by the fixture for PropertyOneArboretum
Sorry, I can't reproduce that. If I run the code in my answer, the PropertyOne values are different.Acrilan
I think I misunderstood your answer (the part about populating PropertyOne first), it's working for me now.Arboretum
No worries, I finally got down in front of some code and figured out what the issue was. See my updated answer.Acrilan
It completely works, but I think I might go with Select in the end. Thank you!Arboretum
A
10

Something like this ought to do it, although you may need to first populate o.PropertyOne:

var fixture = new Fixture();
var objs = fixture
    .Build<MyObject>()
    .Without(o => o.PropertyOne)
    .Without(o => o.PropertyTwo)
    .Do(o =>
        {
            o.PropertyOne = fixture.Create<double>();
            o.PropertyTwo = o.PropertyOne;
        })
    .CreateMany()
    .ToList();

If, however, PropertyTwo depends on PropertyOne, wouldn't it be better to implement that rule as part of the design of the object?

Acrilan answered 12/7, 2017 at 15:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.