Customize AutoFixture property generation using constrained random values

血红的双手。 提交于 2019-12-13 06:31:24

问题


Context

I would like to create a collection of my class, but some of its string property has constrained values. I would like to those values to be still random within the constrained set.

I figured out the customization way, but my the random generation implementation seems to be not using any AutoFixture feature, and I do not want to reinvent the wheel:

var random = new Random();
var fixture = new Fixture();
fixture.Customize<MyClass>(b => b
    .With(i => i.MyProperty, random.Next(2) == 0 ? "O" : "C"));

var result = fixture.CreateMany<MyClass>(1000);

Question

Is there any more efficient way to tell AutoFixture that I would like a random string "O" or "C"?

Edit

Meanwhile I realized that the code above does not work at all, so it do not qualify as "backup" plan. (The expression: random.Next(2) == 0 ? "O" : "C" evaluates only once)


回答1:


Since AutoFixture 4.6.0 you can use callbacks inside the With customization function. That allows to constrain the field value, but let it still vary among the created specimens.

Example of source code:

[Fact]
public void CustomizeMany()
{
    var fixture = new Fixture();
    var items = fixture.Build<MyClass>()
        .With(x => x.EvenNumber, (int number) => number * 2)
        .CreateMany(1000)
        .ToArray();

    Assert.All(items, item => Assert.Equal(0, item.EvenNumber % 2));
}

public class MyClass
{
    public int EvenNumber { get; set; }
}

You can adjust the sample to meet your particular needs.



来源:https://stackoverflow.com/questions/53665164/customize-autofixture-property-generation-using-constrained-random-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!