I use Bogus library for 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 generate list of predefined faker in bogus ?
You can also use the f.Make()
method to generate a list of things. Here is how:
void Main()
{
var Ids = 0;
var test = new Faker<Person>()
.RuleFor(p => p.Id, f => Ids++)
.RuleFor(p => p.Phones, f => f.Make(3, () => f.Phone.PhoneNumber()));
//If you want a variable number of phone numbers
//in the list, replace 3 with f.Random.Number()
test.Generate(5).Dump();
}
public class Person
{
public int Id { get; set; }
public List<string> Phones { get; set; }
}
Hope that helps!
The Bogus library has a helper method for picking a random element of a collection:
public T PickRandom<T>(IEnumerable<T> items)
The method takes an IEnumerable
, which means you can create an Array or a List<string>
to hold your predefined data. You can use it in conjunction with a collection initializer to generate your phone list like this:
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 generate many more entries in your list and you don't want your initializer to grow large (or you want to vary the amount programatically) 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 in the readme on the project's GitHub page.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With