With Bogus, how do you build a Faker<Patient> that generates realistic patient records for an ASP.NET Core clinic-scheduling test suite?
answer
- one rule per property
- the f parameter is the data hub
- (f, p) sees earlier properties
- Generate() or Generate(count)
- StrictMode(true) catches new properties
basics
~10 sCreate new Faker<Patient>() and add a RuleFor per property, drawing values from the Faker hub (f.Name.FirstName(), f.Internet.Email(...), f.Date.PastDateOnly(...)). Generate() returns one patient and Generate(50) a list; StrictMode(true) fails when a property has no rule.
solid answer
~40 sBogus's `Faker<T>` is a reusable recipe. I declare `new Faker<Patient>()` once, usually in a static helper, and add `.RuleFor(p => p.FirstName, f => f.Name.FirstName())` for each property. The `f` parameter is the `Faker` hub with data sets such as `Name`, `Internet`, `Phone`, `Date` and `Random`; the two-argument overload `(f, p) => f.Internet.Email(p.FirstName, p.LastName)` reads properties set by earlier rules, so rules run in the order declared. `Generate()` returns one `Patient` and `Generate(50)` a `List<Patient>`. By default `Faker<T>` calls `Activator.CreateInstance<T>()`, so a record with a primary constructor needs `CustomInstantiator`. `StrictMode(true)` makes generation throw `ValidationException` when a property has no rule, which catches a new column nobody added to the faker. A test that needs one specific value calls `Clone()` and overrides that single rule, rather than mutating the shared faker.
code
csharp · 18 linespublic static class PatientFakers
{
public static Faker<Patient> Default { get; } = new Faker<Patient>()
.StrictMode(true)
.RuleFor(p => p.Id, f => f.Random.Guid())
.RuleFor(p => p.FirstName, f => f.Name.FirstName())
.RuleFor(p => p.LastName, f => f.Name.LastName())
.RuleFor(p => p.Email, (f, p) => f.Internet.Email(p.FirstName, p.LastName))
.RuleFor(p => p.DateOfBirth, f => f.Date.PastDateOnly(90))
.RuleFor(p => p.Phone, f => f.Phone.PhoneNumber("###-###-####"))
.RuleFor(p => p.Status, f => f.PickRandom<PatientStatus>());
}
// in a test
var crowd = PatientFakers.Default.Generate(50);
var okafor = PatientFakers.Default.Clone()
.RuleFor(p => p.LastName, "Okafor")
.Generate();go deeper
Recall the shape: new Faker<Patient>(), one RuleFor per property using the f hub, then Generate() or Generate(count).
Explain the details: the (f, p) overload and declaration order, CustomInstantiator for constructors, StrictMode and Ignore, and why Clone() protects a shared faker.
Organise test data for a suite: one faker per aggregate, builders where invariants matter, and assertions on behaviour rather than on generated literals.
Decide how much realism the suite pays for: generated data finds formatting and length bugs, while explicit builders keep intent readable; set the convention once.
## What Bogus is for A clinic-scheduling API stores patients, clinicians and appointments. Tests need many plausible patients: names that look like names, e-mail addresses that pass validation, dates of birth in a sensible range. Typing them by hand produces the same three records in every test; **Bogus** (the `Bogus` NuGet package, MIT-licensed, a .NET port of faker.js) generates them from rules and locale data sets. ## The two types - **`Faker`** is the **hub** of data sets: `f.Name`, `f.Internet`, `f.Phone`, `f.Address`, `f.Date`, `f.Random`, `f.Lorem` and more, plus helpers such as `f.PickRandom(...)`. It also has `f.Person`, one consistent fake person whose name, e-mail and date of birth belong together. - **`Faker<T>`** is a **typed recipe** for `T`. You configure it with fluent calls and then generate objects from it. ## Writing the rules ```csharp var patients = new Faker<Patient>() .StrictMode(true) .RuleFor(p => p.Id, f => f.Random.Guid()) .RuleFor(p => p.FirstName, f => f.Name.FirstName()) .RuleFor(p => p.LastName, f => f.Name.LastName()) .RuleFor(p => p.Email, (f, p) => f.Internet.Email(p.FirstName, p.LastName)) .RuleFor(p => p.DateOfBirth, f => f.Date.PastDateOnly(90)) .RuleFor(p => p.Phone, f => f.Phone.PhoneNumber("###-###-####")) .RuleFor(p => p.Status, f => f.PickRandom<PatientStatus>()); ``` - **`RuleFor(property, f => ...)`** sets one property from the hub. - **`RuleFor(property, (f, p) => ...)`** also receives the object being built, so a rule can depend on properties set by **earlier** rules; the e-mail above uses the generated names. - **`RuleFor(property, value)`** sets a constant. - **`f.PickRandom<TEnum>()`** picks an enum value; `f.PickRandom(items)` picks from a list. - A second `RuleFor` for the same property **replaces** the first. ## Generating 1. `Generate()` returns one `Patient`. 2. `Generate(50)` returns a `List<Patient>` of 50. 3. `GenerateLazy(n)` and `GenerateForever()` return sequences produced on demand. A `Faker<Patient>` also converts implicitly to `Patient`, which is handy in object initialisers but easy to miss in review. ## Construction and strictness By default `Faker<T>` creates each object with `Activator.CreateInstance<T>()`, which needs a parameterless constructor. A `record Patient(Guid Id, string FirstName, ...)` instead uses `.CustomInstantiator(f => new Patient(f.Random.Guid(), f.Name.FirstName(), ...))`. `StrictMode` is off by default (`Faker.DefaultStrictMode = false`), so a property with no rule is left at its default: `null`, `0`, `default(DateOnly)`. With `StrictMode(true)`, generating throws Bogus's `ValidationException`, listing the missing members. That turns "someone added `InsuranceNumber` to `Patient`" into a failing test instead of a silent null. `Ignore(p => p.Appointments)` marks a member that should stay unset. ## Fakers, builders and the shared-instance trap A faker usually lives in one place, such as a static `PatientFakers` class, so every test draws from the same realistic recipe. Tests then need **one** specific value: the patient whose surname the search endpoint must find. Two approaches: | Approach | How | Watch out for | |---|---|---| | Override a rule | `PatientFakers.Default.Clone().RuleFor(p => p.LastName, "Okafor").Generate()` | without `Clone()` the shared faker is changed for every later test | | Test data builder | a `PatientBuilder` with `WithLastName(...)` and `Build()` that starts from a generated patient | more code, but intention-revealing names | `RuleFor` mutates the faker and returns the same instance, which is why `Clone()` matters. A builder wraps the faker behind methods named after the test's intent, so the test reads `new PatientBuilder().WithLastName("Okafor").Build()` and shows only the value it cares about. ## What to assert Generated values are noise by design. Assert on what the code did with them (the endpoint returned the patient whose surname was set explicitly, the e-mail was stored) rather than on literal generated values, which change whenever the rules or the Bogus version change. ## Mistakes that show up in review - **Expecting automatic filling.** Bogus fills only members with rules; without `StrictMode(true)` a forgotten rule silently produces `null`. - **Values from outside the hub.** `f => Guid.NewGuid()` or `f => DateTime.Now` works, but bypasses the faker's random source and its time reference, which matters as soon as a test needs repeatable data. - **Fixed formats that do not match validation.** `f.Phone.PhoneNumber()` follows the locale's formats; if the API validates a specific pattern, pass a format string such as `"###-###-####"`. - **One faker per test.** Re-declaring the same twenty rules in every test file spreads the recipe; keep one faker per entity and clone it. - **Locale surprises.** `new Faker<Patient>("de")` draws names and addresses from that locale's data, falling back to English data sets the locale lacks; the default is `en`.
- Why call Clone() before overriding a rule on a shared Faker<Patient>?`RuleFor` changes the faker it is called on and returns that same instance. Calling `PatientFakers.Default.RuleFor(p => p.LastName, "Okafor")` would make every later patient an Okafor, in whichever test runs next, which is an order-dependent failure. `Clone()` copies the rules, strict modes and any local seed into a new faker, so the override stays local.
- How do you generate a patient with appointments without looping forever?Use a second faker for `Appointment` and compose it in a rule: `.RuleFor(p => p.Appointments, (f, p) => AppointmentFakers.For(p.Id).Generate(f.Random.Int(0, 3)))`. Bogus never follows navigation properties on its own; it fills exactly the members that have rules, so cycles only appear if a rule creates them.
- When would you choose a hand-written builder over Bogus?When the object's validity rules matter more than its realism, for example an appointment that must not overlap a clinician's slot. A builder encodes those invariants once, behind names such as `ForClinician(...)` and `StartingAt(...)`, and can still use a faker for the fields nobody cares about.
- Bogus fills every property automatically, so RuleFor is only needed for special cases.
- Call RuleFor on the shared static faker inside a test to tweak one patient.
- Faker<T> can construct a positional record without CustomInstantiator.
- StrictMode(true) is the default, so missing rules already fail.
- Assert that the generated patient's first name equals the literal value seen in a run.
- Rules run in alphabetical order of property name, so (f, p) can read any property.