简体   繁体   English

使用受约束的随机值自定义AutoFixture属性生成

[英]Customize AutoFixture property generation using constrained random values

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: 我想出了自定义方式,但是我的随机生成实现似乎没有使用任何AutoFixture功能,并且我不想重新发明轮子:

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"? 有没有更有效的方式告诉AutoFixture我想要一个随机字符串“ O”或“ 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) (表达式:random.Next(2)== 0?“ O”:“ C”仅计算一次)

Since AutoFixture 4.6.0 you can use callbacks inside the With customization function. AutoFixture 4.6.0开始,您可以在With自定义功能内使用回调。 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. 您可以调整样本以满足您的特定需求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM