Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting one property based on another in AutoFixture

Tags:

c#

autofixture

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.

like image 949
yinnonsanders Avatar asked Mar 08 '23 15:03

yinnonsanders


1 Answers

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?

like image 119
Mark Seemann Avatar answered Mar 20 '23 07:03

Mark Seemann