How to generate a list of strings with a Bogus library in C #?

I use the Bogus library to generate test data.

For example, I have a class:

public class Person { public int Id {get; set;} public List<string> Phones {get; set;} // PROBLEM !!! } var Ids = 0; var test = new Faker<Person>() .RuleFor(p => p.Id, f => Ids ++) .RuleFor(p => p.Phones , f => /*HOW ?????*/) // How can I return random list of PhoneNumbers ??? 

Can anyone guide me? How to generate a list of predefined fakers in dummy?

+6
source share
1 answer

The Bogus library has a helper method for selecting a random item in a collection:

 public T PickRandom<T>(IEnumerable<T> items) 

The method accepts IEnumerable , which means you can create an Array or List<string> to store the predefined data. You can use it together with the collection initializer to generate your phone list as follows:

 var phones = new List<string> { "111-111-111", "222-222-222", "333-333-333" }; var Ids = 0; var test = new Faker<Person>() .RuleFor(p => p.Id, f => Ids++) // generate 2 phones .RuleFor(p => p.Phones, f => new List<string> { f.PickRandom(phones), f.PickRandom(phones) }); 

If you want to create many more entries in your list, and you do not want your initializer to increase (or you want to vary the number programmatically), you can use Linq:

 // generate 8 phones .RuleFor(p => p.Phones, f => Enumerable.Range(1, 8).Select(x => f.PickRandom(phones)).ToList()); // generate 1 to 5 phones .RuleFor(p => p.Phones, f => Enumerable.Range(1, f.Random.Int(1, 5)).Select(x => f.PickRandom(phones)).ToList()); 

You can find out more at readme on the GitHub project page.

+5
source

Source: https://habr.com/ru/post/1012675/


All Articles