Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How generate list of string with Bogus library in C#?

Tags:

c#

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 ?

like image 510
NBM Avatar asked Nov 26 '16 17:11

NBM


2 Answers

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

Results using .Make in Bogus

Hope that helps!

like image 182
Brian Chavez Avatar answered Nov 10 '22 19:11

Brian Chavez


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.

like image 43
apk Avatar answered Nov 10 '22 19:11

apk