Can I Set the Country in Bogus (C#)

5.9k views Asked by At

I've just started working with Bogus in C# .net 5.0. I am managing to return very usable data in a sandbox app but I want to restrict the the data to be USA based. Is there a way to do this? (here's part of my sandbox app)

using Bogus;

namespace FrankenPeople
{
    public class GetBogus
    {
        public enum Gender
        {
            Male,
            Female
        }

        private static int userId = 1;

        private static readonly Faker<Person> fakeData = new Faker<Person>()
            .RuleFor(p => p.Id, f => userId++)
            .RuleFor(p => p.Gender, f => f.PickRandom<Gender>().ToString())
            .RuleFor(p => p.Title, f => f.Name.Prefix(f.Person.Gender))
            .RuleFor(p => p.FirstName, f => f.Name.FirstName(f.Person.Gender))
            .RuleFor(p => p.MiddleName, f => f.Name.FirstName(f.Person.Gender))
            .RuleFor(p => p.LastName, f => f.Name.LastName(f.Person.Gender))
            .RuleFor(p => p.StreetAddress, f => f.Address.StreetAddress())
            .RuleFor(p => p.StreetName, f => f.Address.StreetName())
            .RuleFor(p => p.City, f => f.Address.City())
            .RuleFor(p => p.State, f => f.Address.State())
            .RuleFor(p => p.Country, f => f.Address.Country())
            .RuleFor(p => p.ZipCode, f => f.Address.ZipCode())
            .RuleFor(p => p.Phone, f => f.Phone.PhoneNumber("(###)-###-####"))
            .RuleFor(p => p.Email, (f, p) => f.Internet.Email(p.FirstName, p.LastName))
            .RuleFor(p => p.SSN, f => f.Random.Replace("###-##-####"))
            .RuleFor(p => p.DOB, f => f.Date.Past(18))
        ;
        public static Faker<Person> FakeData => fakeData;
    }
}
2

There are 2 answers

1
Alenros On BEST ANSWER

Using locales you can get addresses, domain suffixes and phone numbers:

var faker = new Faker("en_US");
0
Brian Chavez On

By default, Bogus uses the en locale which is roughly USA based. If you want to lock things down as much as possible to USA, then use the en_US locale.

Specifically, in your code example, to specify a locale other than the default, change:

fakeData = new Faker<Person>()   //default is `en`
             ...

to

fakeData = new Faker<Person>(locale: "en_US")
             ...

Locales are not 100% perfect, please be sure to read the small note in this section of the README file: https://github.com/bchavez/Bogus#locales

Note: Some locales may not have a complete data set. For example, zh_CN does not have a lorem data set, but ko has a lorem data set. Bogus will default to en if a locale-specific data set is not found. To further illustrate the previous example, the missing zh_CN:lorem data set will default to the en:lorem data set.