Search code examples
c#fixture

Is it possible with Fixture to create a list of N objects?


I want to create with Fixture a list of N objects.

I know I can do it with:

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

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

Is there any way I can use the CreateMany() method or some other method in order to avoid the loop?


Solution

  • I have done it people.

    /// <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
    }