bchavez / Bogus

:card_index: A simple fake data generator for C#, F#, and VB.NET. Based on and ported from the famed faker.js.
Other
8.72k stars 496 forks source link

Is there a way to produce random addresses that are country specific? #318

Closed tLashbrooke closed 4 years ago

tLashbrooke commented 4 years ago

Trying to generate addresses unique to the UK i.e. country can only be England, Wales, Scotland, Northern Ireland. Counties seems to work. The code I'm using is below, but it's printing out random country names in English

var LocalAddress = new Bogus.DataSets.Address(locale: "en_GB");
            var Name = new Bogus.DataSets.Name(locale: "en_GB");

            this.FirstName = Name.FirstName();
            this.LastName = Name.LastName();

            this.Country = LocalAddress.Country();
            this.County = LocalAddress.County();

            this.HouseNumber = LocalAddress.BuildingNumber();
            this.StreetName = LocalAddress.StreetName();
            this.City = LocalAddress.City();

            this.PostCode = LocalAddress.ZipCode();`

image

bchavez commented 4 years ago

Hi Thomas,

It looks like the faker.js en_GB countries don't tie into any of the normal/main APIs that faker.js exposes.

https://github.com/bchavez/Bogus/blob/4f65c5e108e9b9c9a11ea5a6e9b5445696825202/Source/Bogus/data/en_GB.locale.json#L76-L87

I think you'll have to resort to using the following workaround:

void Main()
{
   var f = new Faker("en_GB");

   var country = f.Address.UkCountry();
   country.Dump();

   var country2 = f.Address.UkCountry2();
   country2.Dump();
}

public static class AddressExtensionsForUk
{
   public static string UkCountry(this Bogus.DataSets.Address address)
   {
      var countries = new [] {
         "England",
         "Scotland",
         "Wales",
         "Northern Ireland"
       };

      return address.Random.ArrayElement(countries);
   }

   public static string UkCountry2(this Bogus.DataSets.Address address){

      var array = Database.Get(nameof(address), "uk_country", "en_GB") as BArray;
      return address.Random.ArrayElement(array);
   }
}

image

Hope that helps!

Thanks, Brian

bchavez commented 4 years ago

Hi Thomas,

Added Address.CountryOfUnitedKingdom() extension method in Bogus.Extensions.UnitedKingdom.

The following code now works in Bogus v30.0.3: https://www.nuget.org/packages/Bogus/30.0.3

using Bogus.Extensions.UnitedKingdom;

void Main()
{
   var f = new Faker("en_GB");
   var uk_country = f.Address.CountryOfUnitedKingdom();

   uk_country.Dump();
}

image

Update to v30.0.3 and give it try. Let me know how it goes! I hope that helps!

Thanks, Brian

tLashbrooke commented 4 years ago

Awesome! Thanks for your help 👍