Fixture 是否可以创建 N 个对象的列表?

Efs*_*dis 3 c# fixture

我想用 Fixture 创建一个包含 N 个对象的列表。

我知道我可以做到:

List<Person> persons = new List<Person>();

for (int i = 0; i < numberOfPersons; i++)
{
    Person person = fixture.Build<Person>().Create();
    persons.Add(person);
}
Run Code Online (Sandbox Code Playgroud)

有什么方法可以使用该CreateMany()方法或其他方法来避免循环?

thu*_*eys 6

你可以使用 linq:

  List<Person> persons = Enumerable.Range(0, numberOfPersons)
            .Select(x => fixture.Build<Person>().Create())
            .ToList();
Run Code Online (Sandbox Code Playgroud)


小智 6

是的,当然,您可以使用CreateMany作为下一个示例:

var numberOfPersons = 10; //Or your loop length number
var fixture = new Fixture();
var person = fixture.CreateMany<Person>(numberOfPersons).ToList(); 
//ToList() to change  the IEnumerable to List
Run Code Online (Sandbox Code Playgroud)


Efs*_*dis 5

找到了答案。CreateMany 有一些获得“计数”的重载。

谢谢人们。


Efs*_*dis 0

我已经做到了人们。

/// <summary>
/// This is a class containing extension methods for AutoFixture.
/// </summary>
public static class AutoFixtureExtensions
{
    #region Extension Methods For IPostprocessComposer<T>

    public static IEnumerable<T> CreateSome<T>(this IPostprocessComposer<T> composer, int numberOfObjects)
    {
        if (numberOfObjects < 0)
        {
            throw new ArgumentException("The number of objects is negative!");
        }

        IList<T> collection = new List<T>();

        for (int i = 0; i < numberOfObjects; i++)
        {
            collection.Add(composer.Create<T>());
        }

        return collection;
    }

    #endregion
}
Run Code Online (Sandbox Code Playgroud)