### Run Bogus Example
Source: https://github.com/bchavez/bogus/blob/master/Examples/ExtendingBogus/README.md
Execute the Bogus example project to see custom fake data generated and printed to the console.
```bash
dotnet restore
dotnet build
dotnet run
```
--------------------------------
### Install Bogus NuGet Package
Source: https://context7.com/bchavez/bogus/llms.txt
Install the Bogus library using the NuGet Package Manager. Minimum requirements include .NET Standard 1.3, .NET Standard 2.0, or .NET Framework 4.0.
```powershell
Install-Package Bogus
```
--------------------------------
### Generated Order Object Example
Source: https://github.com/bchavez/bogus/blob/master/README.md
An example output of a generated Order object, demonstrating the structure and typical data produced by the different Bogus usage methods.
```json
{
"OrderId": 61,
"Item": "vel est ipsa",
"Quantity": 7
}
```
--------------------------------
### Extra Analyzer Setup for Visual Studio for Mac
Source: https://github.com/bchavez/bogus/wiki/Bogus-Premium
For Visual Studio for Mac, add this Analyzer reference to your .csproj file. Replace '25.0.4' with the actual version of the analyzer package you are using.
```xml
```
--------------------------------
### Install Mono Development Package on Linux
Source: https://github.com/bchavez/bogus/wiki/Bogus-Premium
For Visual Studio Code users on Linux, install the mono-devel package to ensure OmniSharp can utilize a full Mono runtime.
```bash
apt install mono-devel
```
--------------------------------
### Using Korean Locale in Bogus
Source: https://github.com/bchavez/bogus/blob/master/README.md
Example of initializing Bogus with a Korean locale ('ko') to generate Korean text. Note that some locales may have incomplete data sets and will default to 'en'.
```csharp
using Bogus.DataSets;
[Test]
public void With_Korean_Locale()
{
var lorem = new Bogus.DataSets.Lorem(locale: "ko");
Console.WriteLine(lorem.Sentence(5));
}
/* 국가는 무상으로 행위로 의무를 구성하지 신체의 처벌받지 예술가의 경우와 */
```
--------------------------------
### Add Bogus.Tools.Analyzer to .csproj
Source: https://github.com/bchavez/bogus/wiki/Bogus-Premium
Include this item group in your .csproj file to add the Bogus.Tools.Analyzer package. Ensure the version number matches your installed package.
```xml
```
--------------------------------
### Execute Gulp Task to Import Locales
Source: https://github.com/bchavez/bogus/wiki/Creating-Locales
After modifying locale files in the `data_extend` directory, run the `gulp importLocales` command from the `Source/Builder` directory to merge your changes into the `data` folder. Ensure Node.js and Gulp are installed globally.
```bash
C:\Bogus\Source\Builder> gulp importLocales
```
--------------------------------
### Faker.CustomInstantiator — Custom Object Construction
Source: https://context7.com/bchavez/bogus/llms.txt
Illustrates how to use `CustomInstantiator` for objects that require constructor arguments or complex initialization. This example shows creating a `Product` object with an ID and SKU from the constructor.
```APIDOC
## Faker.CustomInstantiator — Custom Object Construction
Use `CustomInstantiator` when the object under test requires constructor arguments or complex initialization.
```csharp
public class Product
{
public int Id { get; }
public string Sku { get; }
public string Name { get; set; }
public decimal Price { get; set; }
public Product(int id, string sku)
{
Id = id;
Sku = sku;
}
}
var productId = 0;
var productFaker = new Faker()
.CustomInstantiator(f => new Product(productId++, f.Random.Replace("SKU-###-????")))
.RuleFor(p => p.Name, f => f.Commerce.ProductName())
.RuleFor(p => p.Price, f => f.Finance.Amount(1, 500));
var product = productFaker.Generate();
// product.Id => 0
// product.Sku => "SKU-473-BQMZ"
// product.Name => "Handmade Soft Shirt"
// product.Price => 247.85m
```
```
--------------------------------
### Generate Deterministic Orders with Seed
Source: https://github.com/bchavez/bogus/blob/master/README.md
Use `Faker.UseSeed(int)` to generate deterministic data for a POCO object. This example shows generating a list of `Order` objects with seeded quantities.
```csharp
var orderIds = 0;
var orderFaker = new Faker()
.RuleFor(o => o.OrderId, f => orderIds++)
.RuleFor(o => o.Item, f => f.Commerce.Product())
.RuleFor(o => o.Quantity, f => f.Random.Number(1, 5));
Order SeededOrder(int seed){
return orderFaker.UseSeed(seed).Generate();
}
var orders = Enumerable.Range(1, 5)
.Select(SeededOrder)
.ToList();
orders.Dump();
```
--------------------------------
### Maintain Determinism with Rule Order
Source: https://github.com/bchavez/bogus/blob/master/README.md
To ensure maximum deterministic behavior, add new `RuleFor` rules at the end of the `Faker` declaration. This example demonstrates adding a `Description` rule after quantity, preserving the determinism of `Item` and `Quantity`.
```csharp
var orderIds = 0;
var orderFaker = new Faker()
.RuleFor(o => o.OrderId, f => orderIds++)
.RuleFor(o => o.Item, f => f.Commerce.Product())
.RuleFor(o => o.Quantity, f => f.Random.Number(1, 5))
.RuleFor(o => o.Description, f => f.Commerce.ProductAdjective()); //New Rule
Order MakeOrder(int seed){
return orderFaker.UseSeed(seed).Generate();
}
var orders = Enumerable.Range(1,5)
.Select(MakeOrder)
.ToList();
orders.Dump();
```
--------------------------------
### Guid
Source: https://github.com/bchavez/bogus/blob/master/README.md
Get a random GUID (Globally Unique Identifier).
```APIDOC
## Guid
### Description
Get a random GUID (Globally Unique Identifier).
### Method
Not applicable (SDK method)
### Request Example
```csharp
var randomGuid = Bogus.Guid();
```
### Response
- **GUID** (Guid) - A randomly generated GUID.
```
--------------------------------
### Uuid
Source: https://github.com/bchavez/bogus/blob/master/README.md
Get a random GUID. This is an alias for Randomizer.Guid().
```APIDOC
## Uuid
### Description
Get a random GUID. This is an alias for Randomizer.Guid().
### Method
Not applicable (SDK method)
### Request Example
```csharp
var randomUuid = Bogus.Uuid();
```
### Response
- **UUID** (Guid) - A randomly generated GUID.
```
--------------------------------
### Basic VB.NET Customer Generation with Bogus
Source: https://github.com/bchavez/bogus/blob/master/README.md
Demonstrates how to define a Customer class and use Bogus to generate fake data for its properties using RuleFor and Rules methods. Ensure Bogus is imported.
```vbnet
Imports Bogus
Public Class Customer
Public Property FirstName() As String
Public Property LastName() As String
Public Property Age() As Integer
Public Property Title() As String
End Class
Sub Main
Dim faker As New Faker(Of Customer)
'-- Make a rule for each property
faker.RuleFor( Function(c) c.FirstName, Function(f) f.Name.FirstName) _
.RuleFor( Function(c) c.LastName, Function(f) f.Name.LastName) _
_
.Rules( Sub(f, c) '-- Or, alternatively, in bulk with .Rules()
c.Age = f.Random.Int(18,35)
c.Title = f.Name.JobTitle()
End Sub )
faker.Generate.Dump
End Sub
' OUTPUT:
' FirstName: Jeremie
' LastName: Mills
' Age: 32
' Title: Quality Supervisor
```
--------------------------------
### Execute Benchmark
Source: https://github.com/bchavez/bogus/blob/master/Source/Benchmark/README.md
Run the compiled benchmark executable from the command line after building the project in Release mode. The results will be stored in the BenchmarkDotNet.Artifacts directory.
```bash
dotnet benchmark bin\Release\netstandard2.0\Benchmark.dll
```
--------------------------------
### Compile Benchmark Project in Release Mode
Source: https://github.com/bchavez/bogus/blob/master/Source/Benchmark/README.md
Build the Benchmark project using the .NET CLI, ensuring it is compiled in Release mode for accurate performance measurements. This command is essential before running the benchmarks.
```bash
dotnet build -c Release
```
--------------------------------
### Using DataSets Directly in Bogus
Source: https://github.com/bchavez/bogus/blob/master/README.md
Shows how to generate an Order object by directly using Bogus.Randomizer and Bogus.DataSets.Lorem. This approach provides more granular control over data generation.
```csharp
using Bogus;
using Bogus.DataSets;
public void Using_DataSets_Directly()
{
var random = new Bogus.Randomizer();
var lorem = new Bogus.DataSets.Lorem("en");
var o = new Order()
{
OrderId = random.Number(1, 100),
Item = lorem.Sentence(),
Quantity = random.Number(1, 10)
};
o.Dump();
}
```
--------------------------------
### Generate Fake Orders and Users in C#
Source: https://github.com/bchavez/bogus/blob/master/README.md
Demonstrates how to define and generate fake 'Order' and 'User' objects using Bogus. Includes setting randomizer seeds, defining rules for properties, and custom instantiation. Use this for setting up test data or populating databases.
```csharp
public enum Gender
{
Male,
Female
}
//Set the randomizer seed if you wish to generate repeatable data sets.
Randomizer.Seed = new Random(8675309);
var fruit = new[] { "apple", "banana", "orange", "strawberry", "kiwi" };
var orderIds = 0;
var testOrders = new Faker()
//Ensure all properties have rules. By default, StrictMode is false
//Set a global policy by using Faker.DefaultStrictMode
.StrictMode(true)
//OrderId is deterministic
.RuleFor(o => o.OrderId, f => orderIds++)
//Pick some fruit from a basket
.RuleFor(o => o.Item, f => f.PickRandom(fruit))
//A random quantity from 1 to 10
.RuleFor(o => o.Quantity, f => f.Random.Number(1, 10))
//A nullable int? with 80% probability of being null.
//The .OrNull extension is in the Bogus.Extensions namespace.
.RuleFor(o => o.LotNumber, f => f.Random.Int(0, 100).OrNull(f, .8f));
var userIds = 0;
var testUsers = new Faker()
//Optional: Call for objects that have complex initialization
.CustomInstantiator(f => new User(userIds++, f.Random.Replace("###-##-####")))
//Use an enum outside scope.
.RuleFor(u => u.Gender, f => f.PickRandom())
//Basic rules using built-in generators
.RuleFor(u => u.FirstName, (f, u) => f.Name.FirstName(u.Gender))
.RuleFor(u => u.LastName, (f, u) => f.Name.LastName(u.Gender))
.RuleFor(u => u.Avatar, f => f.Internet.Avatar())
.RuleFor(u => u.UserName, (f, u) => f.Internet.UserName(u.FirstName, u.LastName))
.RuleFor(u => u.Email, (f, u) => f.Internet.Email(u.FirstName, u.LastName))
.RuleFor(u => u.SomethingUnique, f => $"Value {f.UniqueIndex}")
//Use a method outside scope.
.RuleFor(u => u.CartId, f => Guid.NewGuid())
//Compound property with context, use the first/last name properties
.RuleFor(u => u.FullName, (f, u) => u.FirstName + " " + u.LastName)
//And composability of a complex collection.
.RuleFor(u => u.Orders, f => testOrders.Generate(3).ToList())
//Optional: After all rules are applied finish with the following action
.FinishWith((f, u) =>
{
Console.WriteLine("User Created! Id={0}", u.Id);
});
var user = testUsers.Generate();
Console.WriteLine(user.DumpAsJson());
/* OUTPUT:
User Created! Id=0
*
{
"Id": 0,
"FirstName": "Audrey",
"LastName": "Spencer",
"FullName": "Audrey Spencer",
"UserName": "Audrey_Spencer72",
"Email": "Audrey82@gmail.com",
"Avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/itstotallyamy/128.jpg",
"CartId": "863f9462-5b88-471f-b833-991d68db8c93",
"SSN": "923-88-4231",
"Gender": 0,
"Orders": [
{
"OrderId": 0,
"Item": "orange",
"Quantity": 8
},
{
"OrderId": 1,
"Item": "banana",
"Quantity": 2
},
{
"OrderId": 2,
"Item": "kiwi",
"Quantity": 9
}
]
} */
```
--------------------------------
### WordsArray
Source: https://github.com/bchavez/bogus/blob/master/README.md
Get a range of words in an array (English).
```APIDOC
## WordsArray
### Description
Get a range of words in an array (English).
### Method
Not applicable (SDK method)
### Parameters
- **count** (int) - The number of words to retrieve.
### Request Example
```csharp
var wordsArray = Bogus.WordsArray(count: 10);
```
### Response
- **Words Array** (string[]) - An array of randomly generated words.
```
--------------------------------
### Words
Source: https://github.com/bchavez/bogus/blob/master/README.md
Gets some random words and phrases in English.
```APIDOC
## Words
### Description
Gets some random words and phrases in English.
### Method
Not applicable (SDK method)
### Request Example
```csharp
var randomWords = Bogus.Words(count: 5);
```
### Response
- **Words** (IEnumerable) - A collection of randomly generated words and phrases.
```
--------------------------------
### Bogus Custom Data Output
Source: https://github.com/bchavez/bogus/blob/master/Examples/ExtendingBogus/README.md
Example output from the Bogus custom data generation, showing generated fake data for 'FaveDrink', 'FaveCandy', and 'PostCode'.
```json
{
"FaveDrink": "Soda",
"FaveCandy": "Jelly bean",
"PostCode": "M4W"
}
```
--------------------------------
### Activate Bogus Premium with Static License Class
Source: https://github.com/bchavez/bogus/wiki/Bogus-Premium
Set the company name and license key using static properties on the `Bogus.Premium.License` class. This method is suitable for extended datasets but does not activate `Bogus.Tools.Analyzer`.
```csharp
Bogus.Premium.License.LicenseTo = "My Company"
Bogus.Premium.License.LicenseKey = "32fjxNYLQas..."
```
--------------------------------
### Generate System and File Data with Faker.System
Source: https://context7.com/bchavez/bogus/llms.txt
Generates realistic file names with specified extensions, common file names, file paths, directory paths, MIME types, common file types, semantic version strings, and version objects. Also generates fake exceptions and Android IDs.
```csharp
var f = new Faker();
string fileName = f.System.FileName("pdf"); // "report.pdf"
string commonFile = f.System.CommonFileName(); // "image.jpeg"
string filePath = f.System.FilePath(); // "/home/user/docs/file.txt"
string dirPath = f.System.DirectoryPath(); // "/var/log/app"
string mime = f.System.MimeType(); // "application/json"
string commonMime = f.System.CommonFileType(); // "image"
string ext = f.System.FileExt("image/png"); // "png"
string semver = f.System.Semver(); // "3.1.7"
Version version = f.System.Version(); // Version(2, 4, 1, 0)
Exception ex = f.System.Exception(); // Exception with fake stack trace
string androidId = f.System.AndroidId(); // GCM registration ID
```
--------------------------------
### Using Faker Facade in Bogus
Source: https://github.com/bchavez/bogus/blob/master/README.md
Demonstrates using the Faker facade to generate an Order object with random data. This method is suitable for quick data generation without explicit DataSet instantiation.
```csharp
public void Using_The_Faker_Facade()
{
var faker = new Faker("en");
var o = new Order()
{
OrderId = faker.Random.Number(1, 100),
Item = faker.Lorem.Sentence(),
Quantity = faker.Random.Number(1, 10)
};
o.Dump();
}
```
--------------------------------
### Populate Existing Instance with Faker
Source: https://context7.com/bchavez/bogus/llms.txt
Use the Populate method to fill an existing object instance with data generated by Faker, rather than creating a new object. This is useful for updating or reusing existing data structures.
```csharp
public class Config
{
public string Host { get; set; }
public int Port { get; set; }
}
var faker = new Faker()
.RuleFor(c => c.Host, f => f.Internet.DomainName())
.RuleFor(c => c.Port, f => f.Internet.Port());
var existing = new Config { Host = "localhost", Port = 0 };
faker.Populate(existing);
// existing.Host => "bogus-test.com"
// existing.Port => 43812
```
--------------------------------
### Randomizer Primitives
Source: https://context7.com/bchavez/bogus/llms.txt
Provides thread-safe primitive random value generation. Use for seeding and generating various data types like numbers, booleans, GUIDs, and strings. Supports custom seeding for reproducibility.
```csharp
Randomizer.Seed = new Random(42); // global seed for reproducibility
var r = new Randomizer(1234); // local seed, ignores global
int n = r.Number(1, 100); // 1–100 inclusive
double d = r.Double(0.0, 1.0); // 0.0–1.0
bool b = r.Bool(); // true or false
bool weighted = r.Bool(0.8f); // 80% probability of true
Guid id = r.Guid(); // random GUID
string hash = r.Hash(40); // SHA-1 length hex string
string alnum = r.AlphaNumeric(12); // "a3f9kz2m1qpx"
string hex = r.Hexadecimal(8, "0x"); // "0x3fa09c2b"
string ssn = r.Replace("###-##-####"); // "618-19-3064"
string code = r.Replace("##? ??? ####");// "39E SPC 0790"
// Enum selection
Gender gender = r.Enum();
Gender notMale = r.Enum(Gender.Male); // excludes Male
// Collection helpers
var fruits = new[] { "apple", "banana", "cherry" };
string pick = r.ArrayElement(fruits); // random element
string[] subset = r.ArrayElements(fruits, 2); // 2 random elements
var list = new List { 1, 2, 3, 4, 5 };
int item = r.ListItem(list); // random item
IEnumerable shuffled = r.Shuffle(list); // shuffled sequence
// Weighted selection
var items = new[] { "common", "rare", "legendary" };
var weights = new[] { 0.70f, 0.25f, 0.05f };
string loot = r.WeightedRandom(items, weights); // 70% "common"
// Unique index (auto-incremented across all Faker[T] instances)
int idx = f.UniqueIndex; // e.g., 42
int global = f.IndexGlobal; // same as UniqueIndex
int local = f.IndexFaker; // local to this Faker[T] instance
```
--------------------------------
### Add New Property with Seeded Order
Source: https://github.com/bchavez/bogus/blob/master/README.md
When adding a new property to a POCO, place its `RuleFor` at the end of the `Faker` declaration to minimize impact on existing deterministic data. This example adds a `Description` property.
```csharp
var orderIds = 0;
var orderFaker = new Faker()
.RuleFor(o => o.OrderId, f => orderIds++)
.RuleFor(o => o.Item, f => f.Commerce.Product())
.RuleFor(o => o.Description, f => f.Commerce.ProductAdjective()) //New Rule
.RuleFor(o => o.Quantity, f => f.Random.Number(1, 5));
Order SeededOrder(int seed){
return orderFaker.UseSeed(seed).Generate();
}
var orders = Enumerable.Range(1,5)
.Select(SeededOrder)
.ToList();
orders.Dump();
```
--------------------------------
### Generate List of Emails using LINQ - C#
Source: https://github.com/bchavez/bogus/blob/master/README.md
Demonstrates generating a list of email addresses using a combination of Enumerable.Range(), LINQ's Select method, and the Faker's Internet.Email() generator. The locale is specified as 'en'.
```csharp
using Bogus;
using System.Linq;
var faker = new Faker("en");
var emailList = Enumerable.Range(1, 5)
.Select(_ => faker.Internet.Email())
.ToList();
//OUTPUT:
//Gustave83@hotmail.com
//Evie33@gmail.com
//Abby_Wilkinson@yahoo.com
//Cecilia.Hahn@yahoo.com
//Jasen.Waelchi85@gmail.com
```
--------------------------------
### Bulk Generation with Faker
Source: https://context7.com/bchavez/bogus/llms.txt
Generate single objects, typed lists, lazy enumerables, or infinite streams of data using Generate, GenerateLazy, and GenerateForever. Use GenerateBetween for random counts.
```csharp
var faker = new Faker()
.RuleFor(o => o.OrderId, f => f.IndexFaker)
.RuleFor(o => o.Item, f => f.Commerce.Product())
.RuleFor(o => o.Quantity, f => f.Random.Number(1, 5));
// Generate a single object
Order one = faker.Generate();
// Generate a typed list of 10
List batch = faker.Generate(10);
// Lazy enumerable (deferred, not yet evaluated)
IEnumerable lazy = faker.GenerateLazy(10);
// Infinite stream, take as many as needed
IEnumerable stream = faker.GenerateForever().Take(3);
// GenerateBetween extension: random count between min and max
List variable = faker.GenerateBetween(3, 7);
```
--------------------------------
### Bulk Rules for Faker Configuration - C#
Source: https://github.com/bchavez/bogus/blob/master/README.md
Utilizes the .Rules() shortcut to define multiple rules for a Faker instance in a single block. Note that when using bulk rules, StrictMode cannot be set to true.
```csharp
using Bogus;
public class Order
{
public int OrderId { get; set; }
public string Item { get; set; }
public int Quantity { get; set; }
}
public void create_rules_for_an_object_the_easy_way()
{
var faker = new Faker()
.StrictMode(false)
.Rules((f, o) =>
{
o.Quantity = f.Random.Number(1, 4);
o.Item = f.Commerce.Product();
o.OrderId = 25;
});
Order o = faker.Generate();
}
```
--------------------------------
### Extend Commerce Colors in es Locale
Source: https://github.com/bchavez/bogus/wiki/Creating-Locales
When modifying an existing locale, copy the relevant array from the `data` folder to the `data_extend` folder and append your new data. This example shows adding new colors to the `commerce.color` array for the Spanish locale.
```json
{
"commerce": {
"color": [
"Rojo",
"Azul",
"Verde",
"Morado",
"Violeta",
"My New Color 1",
"My New Color 2",
"My New Color 3"
]
}
}
```
--------------------------------
### Add Bogus.Tools.Analyzer via .NET CLI
Source: https://github.com/bchavez/bogus/wiki/Bogus-Premium
Use this command to add the Bogus.Tools.Analyzer package to your project if you are using the .NET CLI.
```bash
dotnet add package Bogus.Tools.Analyzer
```
--------------------------------
### Direct Dataset Access with Faker Facade
Source: https://context7.com/bchavez/bogus/llms.txt
The Faker class provides direct access to all datasets without requiring a typed model. Use this for quick, ad-hoc data generation.
```csharp
var f = new Faker("en");
string firstName = f.Name.FirstName(); // "Audrey"
string lastName = f.Name.LastName(); // "Spencer"
string email = f.Internet.Email(); // "audrey.spencer@gmail.com"
string url = f.Internet.Url(); // "https://example.com/path"
string ipv4 = f.Internet.Ip(); // "192.168.1.42"
string password = f.Internet.Password(); // "p@ssW0rd!2A"
string city = f.Address.City(); // "New York"
string street = f.Address.StreetAddress(); // "742 Evergreen Terrace"
string country = f.Address.Country(); // "United States"
string product = f.Commerce.ProductName(); // "Handmade Soft Shirt"
decimal price = f.Commerce.Amount(10, 500); // 247.85m
string company = f.Company.CompanyName(); // "Smith & Sons LLC"
string creditCard = f.Finance.CreditCardNumber();// "4916-3389-9992-3426"
Currency currency = f.Finance.Currency(); // { Code: "USD", Symbol: "$" }
string loremText = f.Lorem.Sentence(8); // "Vel est ipsa modi cum..."
string mimeType = f.System.MimeType(); // "application/pdf"
string fileName = f.System.FileName("pdf"); // "report.pdf"
string vin = f.Vehicle.Vin(); // "HJ3KC4Z4MD2P17892"
string phrase = f.Hacker.Phrase(); // "Try to back up the CSS bus..."
```
--------------------------------
### Using Faker Inheritance in Bogus
Source: https://github.com/bchavez/bogus/blob/master/README.md
Illustrates creating a custom OrderFaker class by inheriting from Faker and defining rules for generating Order objects. This is useful for complex object generation with specific configurations.
```csharp
using Bogus;
public class OrderFaker : Faker {
public OrderFaker() {
RuleFor(o => o.OrderId, f => f.Random.Number(1, 100));
RuleFor(o => o.Item, f => f.Lorem.Sentence());
RuleFor(o => o.Quantity, f => f.Random.Number(1, 10));
}
}
public void Using_FakerT_Inheritance()
{
var orderFaker = new OrderFaker();
var o = orderFaker.Generate();
o.Dump();
}
```
--------------------------------
### Rule Validation with Faker
Source: https://context7.com/bchavez/bogus/llms.txt
Use StrictMode, Validate, and AssertConfigurationIsValid to ensure all properties are configured. Strict mode catches missed properties at development time, preventing runtime errors.
```csharp
public class Invoice
{
public int Id { get; set; }
public string Description { get; set; }
public decimal Amount { get; set; }
}
var faker = new Faker()
.StrictMode(true)
.RuleFor(i => i.Id, f => f.IndexFaker)
.RuleFor(i => i.Description, f => f.Lorem.Sentence())
// Intentionally missing: .RuleFor(i => i.Amount, ...)
// Returns false — Amount has no rule
bool isValid = faker.Validate();
// Throws ValidationException listing all missing rules
try
{
faker.AssertConfigurationIsValid();
}
catch (ValidationException ex)
{
Console.WriteLine(ex.Message);
// "There are missing rules for Faker 'Invoice'.
// =========== Missing Rules ===========
// Amount"
}
// Ignore a property explicitly when strict mode is on
faker.Ignore(i => i.Amount);
faker.AssertConfigurationIsValid(); // now passes
```
--------------------------------
### Pick Random Elements and Make Items with Faker
Source: https://context7.com/bchavez/bogus/llms.txt
Use `PickRandom` to select single or multiple elements from a collection. `Make` generates a specified number of items using a lambda, with an optional index parameter for indexed generation. `MakeLazy` provides deferred execution.
```csharp
var f = new Faker();
var fruits = new[] { "apple", "banana", "cherry", "kiwi" };
// Pick one random element
string fruit = f.PickRandom(fruits); // "banana"
// Pick a random enum value
Gender g = f.PickRandom(); // Gender.Female
// Pick a random enum excluding specific values
Gender notFemale = f.PickRandomWithout(Gender.Female); // Gender.Male
// Pick N random elements from a collection
IEnumerable two = f.PickRandom(fruits, 2); // ["cherry", "apple"]
// Make N items via lambda (index-unaware)
IList emails = f.Make(3, () => f.Internet.Email());
// ["a@b.com", "c@d.net", "e@f.org"]
// Make N items with index
IList indexed = f.Make(3, i => $"user_{i}@domain.com");
// ["user_1@domain.com", "user_2@domain.com", "user_3@domain.com"]
// MakeLazy — deferred LINQ execution
IEnumerable lazy = f.MakeLazy(5, () => f.Name.FullName());
```
--------------------------------
### Generate Lorem Ipsum Text with Faker.Lorem
Source: https://context7.com/bchavez/bogus/llms.txt
Generate placeholder text at various granularities (word, sentence, paragraph) using Faker.Lorem. Supports non-English locales and custom separators.
```csharp
var f = new Faker("en");
string word = f.Lorem.Word(); // "exercitationem"
string[] words = f.Lorem.Words(5); // ["qui", "est", "vel", "aut", "id"]
string letter = f.Lorem.Letter(3); // "qae"
string sentence = f.Lorem.Sentence(8); // "Vel est ipsa modi cum..."
string sentences = f.Lorem.Sentences(3); // 3 sentences joined with \n
string para = f.Lorem.Paragraph(4); // paragraph of 4 sentences
string paras = f.Lorem.Paragraphs(2, "
"); // 2 paragraphs separated by
string text = f.Lorem.Text(); // random lorem method output
string lines = f.Lorem.Lines(3); // 3 lines of lorem
string slug = f.Lorem.Slug(4); // "vel-est-ipsa-modi"
// Non-English locale lorem (falls back to 'en' if locale has no lorem data)
var korean = new Bogus.DataSets.Lorem("ko");
string koSentence = korean.Sentence(5);
// "국가는 무상으로 행위로 의무를 구성하지"
```
--------------------------------
### Bulk Property Assignment with Faker.Rules
Source: https://context7.com/bchavez/bogus/llms.txt
Use `Rules` to set multiple properties on an object within a single action block. This is incompatible with `StrictMode(true)`. Ensure `StrictMode` is set to `false` before applying `Rules`.
```csharp
var faker = new Faker()
.StrictMode(false)
.Rules((f, o) =>
{
o.OrderId = f.IndexFaker;
o.Item = f.Commerce.Product();
o.Quantity = f.Random.Number(1, 4);
});
var order = faker.Generate();
// order.OrderId => 0
// order.Item => "Shoes"
// order.Quantity => 3
```
--------------------------------
### Custom Object Construction with Faker.CustomInstantiator
Source: https://context7.com/bchavez/bogus/llms.txt
Use CustomInstantiator for objects requiring constructor arguments or complex initialization. This allows for custom object creation logic before property rules are applied.
```csharp
public class Product
{
public int Id { get; }
public string Sku { get; }
public string Name { get; set; }
public decimal Price { get; set; }
public Product(int id, string sku)
{
Id = id;
Sku = sku;
}
}
var productId = 0;
var productFaker = new Faker()
.CustomInstantiator(f => new Product(productId++, f.Random.Replace("SKU-###-????")))
.RuleFor(p => p.Name, f => f.Commerce.ProductName())
.RuleFor(p => p.Price, f => f.Finance.Amount(1, 500));
var product = productFaker.Generate();
// product.Id => 0
// product.Sku => "SKU-473-BQMZ"
// product.Name => "Handmade Soft Shirt"
// product.Price => 247.85m
```
--------------------------------
### Define Named Rule Sets with Faker
Source: https://context7.com/bchavez/bogus/llms.txt
Use named rule sets to generate objects with different property configurations for various scenarios. Define distinct sets for specific use cases like 'admin' or 'guest' users.
```csharp
public class Account
{
public string Role { get; set; }
public bool IsActive { get; set; }
public string Email { get; set; }
}
var accountFaker = new Faker()
.RuleFor(a => a.Email, f => f.Internet.Email())
.RuleSet("admin", set =>
{
set.RuleFor(a => a.Role, "admin");
set.RuleFor(a => a.IsActive, true);
})
.RuleSet("guest", set =>
{
set.RuleFor(a => a.Role, "guest");
set.RuleFor(a => a.IsActive, false);
});
// Generate with "default" rules only (Email is set, Role/IsActive unset)
var defaultAccount = accountFaker.Generate();
// Generate with "admin" rule set only (Role and IsActive set, Email NOT set)
var adminAccount = accountFaker.Generate("admin");
// Combine rule sets: apply "default" then "admin"
var fullAdmin = accountFaker.Generate("default,admin");
// fullAdmin.Email => "john.doe@gmail.com"
// fullAdmin.Role => "admin"
// fullAdmin.IsActive => true
```
--------------------------------
### Deterministic Generation with Faker
Source: https://context7.com/bchavez/bogus/llms.txt
Ensure consistent data generation by using local seeds with UseSeed or anchoring date calculations with UseDateTimeReference. This isolates randomness and provides predictable results.
```csharp
var faker = new Faker()
.RuleFor(o => o.OrderId, f => f.IndexFaker)
.RuleFor(o => o.Item, f => f.Commerce.Product())
.RuleFor(o => o.Quantity, f => f.Random.Number(1, 5));
// Each seeded call produces the same object for that seed value
Order first = faker.UseSeed(1).Generate(); // Item => "Bike", Quantity => 1
Order second = faker.UseSeed(2).Generate(); // Item => "Cheese", Quantity => 3
// Deterministic dates: anchor date calculations to a fixed point in time
var timedFaker = new Faker()
.UseSeed(42)
.UseDateTimeReference(new DateTime(2024, 1, 1))
.RuleFor(o => o.OrderId, f => f.IndexFaker)
.RuleFor(o => o.Item, f => f.Date.Soon().ToString("yyyy-MM-dd"));
Order timedOrder = timedFaker.Generate();
// timedOrder.Item => "2024-01-01" (deterministic relative to anchor)
```
--------------------------------
### Deterministic Dates and Times with Faker
Source: https://github.com/bchavez/bogus/blob/master/README.md
Set a local seed and a time reference for a Faker instance to generate deterministic dates and times. This is achieved by initializing the `Random` property with a `Randomizer` and setting the `DateTimeReference` property.
```csharp
// Faker: Set a local seed and a time reference
var faker = new Faker
{
Random = new Randomizer(1338),
DateTimeReference = DateTime.Parse("1/1/1980")
};
faker.Date.Soon(); // "1980-01-01T17:33:05"
faker.Date.Recent(); // "1979-12-31T14:07:31"
```
--------------------------------
### Faker - Typed Fake Object Generator
Source: https://context7.com/bchavez/bogus/llms.txt
Demonstrates how to use `Faker` to generate instances of a strongly-typed object (`User`) with custom rules for each property. Includes setting a global seed for deterministic generation and generating single objects or lists.
```APIDOC
## Faker — Typed Fake Object Generator
`Faker` is the primary API for generating fake instances of a class. Rules are declared per property using a fluent chain and objects are emitted via `Generate()`.
```csharp
public enum Gender { Male, Female }
public class User
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string UserName { get; set; }
public Gender Gender { get; set; }
public DateTime DateOfBirth { get; set; }
}
// Set a repeatable global seed
Randomizer.Seed = new Random(8675309);
var userId = 0;
var faker = new Faker()
.StrictMode(true)
.RuleFor(u => u.Id, f => userId++)
.RuleFor(u => u.Gender, f => f.PickRandom())
.RuleFor(u => u.FirstName, (f, u) => f.Name.FirstName(u.Gender == Gender.Male ? Name.Gender.Male : Name.Gender.Female))
.RuleFor(u => u.LastName, f => f.Name.LastName())
.RuleFor(u => u.Email, (f, u) => f.Internet.Email(u.FirstName, u.LastName))
.RuleFor(u => u.UserName, (f, u) => f.Internet.UserName(u.FirstName, u.LastName))
.RuleFor(u => u.DateOfBirth, f => f.Date.Past(30));
User user = faker.Generate();
// user.Id => 0
// user.FirstName => "Audrey"
// user.Email => "Audrey_Spencer72@gmail.com"
List users = faker.Generate(5);
// Returns a list of 5 fake User objects
```
```
--------------------------------
### Faker.System — System and File Data
Source: https://context7.com/bchavez/bogus/llms.txt
Generates realistic file names, MIME types, semver strings, and exceptions. Supports common file names, file paths, directory paths, common file types, file extensions based on MIME type, semantic versioning, and Android IDs.
```APIDOC
## `Faker.System` — System and File Data
Generates realistic file names, MIME types, semver strings, and exceptions.
```csharp
var f = new Faker();
string fileName = f.System.FileName("pdf"); // "report.pdf"
string commonFile = f.System.CommonFileName(); // "image.jpeg"
string filePath = f.System.FilePath(); // "/home/user/docs/file.txt"
string dirPath = f.System.DirectoryPath(); // "/var/log/app"
string mime = f.System.MimeType(); // "application/json"
string commonMime = f.System.CommonFileType(); // "image"
string ext = f.System.FileExt("image/png"); // "png"
string semver = f.System.Semver(); // "3.1.7"
Version version = f.System.Version(); // Version(2, 4, 1, 0)
Exception ex = f.System.Exception(); // Exception with fake stack trace
string androidId = f.System.AndroidId(); // GCM registration ID
```
```
--------------------------------
### Set Local Seed for Faker and DataSets
Source: https://github.com/bchavez/bogus/blob/master/README.md
Configure the `Faker` facade and individual `DataSets` to use local seeds by setting their `Random` property to a new `Randomizer` instance with a specific seed. This ensures independent deterministic behavior.
```csharp
var faker = new Faker("en")
{
Random = new Randomizer(1338)
};
var lorem = new Bogus.DataSets.Lorem("en"){
Random = new Randomizer(1338)
};
faker.Lorem.Word().Dump();
lorem.Word().Dump();
//OUTPUT:
//minus
//minus
```
--------------------------------
### Deterministic Dates and Times with Faker[T]
Source: https://github.com/bchavez/bogus/blob/master/README.md
Set a local seed and a time reference for a Faker[T] instance to generate deterministic dates and times. The `UseSeed` method sets the seed, and `UseDateTimeReference` sets the time reference.
```csharp
// Faker[T]: Set a local seed and a time reference
var fakerT = new Faker()
.UseSeed(1338)
.UseDateTimeReference(DateTime.Parse("1/1/1980"))
.RuleFor(o => o.SoonValue, f => f.Date.Soon())
.RuleFor(o => o.RecentValue, f => f.Date.Recent());
fakerT.Generate().Dump();
// { "SoonValue": "1980-01-01T17:33:05",
// "RecentValue": "1979-12-31T14:07:31" }
```