'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 1:[1]
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
}
Solution 2:[2]
Found the answer. CreateMany has some overloads that get 'count'.
Thanks people.
Solution 3:[3]
you can use linq:
List<Person> persons = Enumerable.Range(0, numberOfPersons)
.Select(x => fixture.Build<Person>().Create())
.ToList();
Solution 4:[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
Solution 5:[5]
var dtos = (new Fixture()).CreateMany<YourObjectType>(numberRecords);
Solution 6:[6]
var people = _fixture
.Build<Person>()
.CreateMany()
.ToList(); // if you want to return a generic list
Solution 7:[7]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Efstathios Chatzikyriakidis |
Solution 3 | |
Solution 4 | Ahmed El-Hansy |
Solution 5 | Grey Wolf |
Solution 6 | Enes Cinar |
Solution 7 |