自定义在AutoFixture中创建匿名序列

时间:2018-06-04 07:54:05

标签: autofixture

使用anonymous sequences,当我不太关心它的数量或类型时,我可以创建一系列对象:

public class Foo { public string Bar { get; set; } }

var fixture = new Fixture();
var foos = fixture.CreateMany<Foo>();

我是否可以通过某种方式自定义此类序列的创建,例如以一种一次考虑整个集合的方式为集合中的每个项目设置一个属性,而不是一次只考虑一个项目?

例如,有没有办法实现以下目标?

public interface ISortable
{
    int SortOrder { get; set; }
}

public class Foo : ISortable
{
    public string Bar { get; set; }
    public int SortOrder { get; set; }
}

var fixture = new Fixture();

// TODO: Customize the fixture here

var foos = fixture.CreateMany<Foo>();

// foos now have sort-order set to e.g. a multiple of their index
// in the list, so if three items, they have sort order 0, 10, 20.

1 个答案:

答案 0 :(得分:1)

It's been a while since I handed over control of AutoFixture, so my information could be out of date, but I don't think there's any feature like that. What I usually do in cases like that is that use normal code to configure what AutoFixture generates. In this particular case, you can use a zip to achieve the desired result; prototype:

[Fact]
public void SetSortOrderOnFoos()
{
    var fixture = new Fixture();
    var foos = fixture
        .CreateMany<Foo>()
        .Zip(
            Enumerable.Range(0, fixture.RepeatCount),
            (f, i) => { f.SortOrder = i * 10; return f; });

    Assert.Equal(3, foos.Count());
    Assert.Equal( 0, foos.ElementAt(0).SortOrder);
    Assert.Equal(10, foos.ElementAt(1).SortOrder);
    Assert.Equal(20, foos.ElementAt(2).SortOrder);
}

This test isn't robust, but I hope it communicates the core idea.