5

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

我知道我可以这样做:

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

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

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

4

6 回答 6

6

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

谢谢人们。

于 2014-10-10T12:22:19.967 回答
4

你可以使用 linq:

  List<Person> persons = Enumerable.Range(0, numberOfPersons)
            .Select(x => fixture.Build<Person>().Create())
            .ToList();
于 2014-10-10T12:22:33.353 回答
1
var dtos = (new Fixture()).CreateMany<YourObjectType>(numberRecords);
于 2018-01-18T02:05:00.800 回答
1

是的,当然,您可以将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
于 2019-01-23T11:14:31.933 回答
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
}
于 2014-10-10T12:56:26.727 回答
0
var people = _fixture
        .Build<Person>()
        .CreateMany()
        .ToList(); // if you want to return a generic list
于 2022-02-17T17:37:23.450 回答