5

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?

Andrey Korneyev
  • 26,353
  • 15
  • 70
  • 71

7 Answers7

7

Found the answer. CreateMany has some overloads that get 'count'.

Thanks people.

6

you can use linq:

  List<Person> persons = Enumerable.Range(0, numberOfPersons)
            .Select(x => fixture.Build<Person>().Create())
            .ToList();
thumbmunkeys
  • 20,606
  • 8
  • 62
  • 110
4

Yes Sure, you can use the CreateMany as the next sample:

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
Ahmed El-Hansy
  • 160
  • 1
  • 15
1
var dtos = (new Fixture()).CreateMany<YourObjectType>(numberRecords);
Wolf
  • 6,361
  • 2
  • 28
  • 25
0

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
}
0
var people = _fixture
        .Build<Person>()
        .CreateMany()
        .ToList(); // if you want to return a generic list
Enes Cinar
  • 41
  • 1
  • 5
0

You can use AutoFixture.CreateMany(n) where n is the numbers of items you want :

var persons = Fixture.CreateMany<Person>(100).ToList();
//persons.Count() = 100

You can also configure AutoFixture with pre-configured numbers of items with RepeatCount :

fixture.RepeatCount = 100;
var persons = fixture.CreateMany<Person>().ToList();
//persons.Count() = 100
Francois Borgies
  • 2,378
  • 31
  • 38