Models: Factories
- Introduction
- Complete Example: Posts for One Author
- Defining Model Factories
- Creating Models Using Factories
- Factory Relationships
Introduction
A factory describes how to make a model with fake data, so tests and seeders can create as many records as they need in one line. Fake values come from Bogus, .NET's port of the faker library Laravel uses, available in a factory as Faker:
using SampleApp.Models;
namespace SampleApp.Database.Factories;
public class UserFactory : Factory<User>
{
// Hashing is deliberately slow; hash the default password once.
static string? password;
public override User Definition() => new()
{
Name = Faker.Name.FullName(),
Email = Faker.Internet.Email(uniqueSuffix: Guid.NewGuid().ToString("N")[..8]),
EmailVerifiedAt = DateTime.UtcNow,
Password = password ??= Hash.Make("password"),
};
public UserFactory Unverified() => (UserFactory)State(u => u.EmailVerifiedAt = null);
}The fake data's language follows app.faker_locale in config/App.cs (for example faker_locale = "id_ID"; default "en").
Defining Model Factories
Generating Factories
dotblaze make:factory PostFactory # the model is inferred from the name
dotblaze make:factory AuditFactory --model=Post
dotblaze make:model Post --factory --migrationFactories live in database/factories. DotBlaze finds a model's factory by its base class (Factory<Post>), so Post.Factory() works without registration.
Factory States
A state is a method that changes the made models. Build it with State, and cast back to your factory so other states can follow:
public UserFactory Suspended() => (UserFactory)State(u => u.SuspendedAt = DateTime.UtcNow);Use your factory's own states through Model.Factory<TFactory>() or new UserFactory():
var user = await User.Factory<UserFactory>().Unverified().Create();
var users = await new UserFactory().Count(3).Suspended().CreateMany();Count, Set, Sequence, For, and Has keep your factory's type, so a custom state may come before or after them. State((model, index) => ...) also receives the model's position.
Factory Callbacks
var users = await User.Factory()
.AfterMaking(u => u.Name = u.Name.ToUpper()) // after Definition and states
.AfterCreating(async u => await u.Notify(new Welcome())) // after saving
.CreateMany(3);Creating Models Using Factories
Instantiating Models
Make builds a model without saving it; MakeMany builds several:
var user = User.Factory().Make();
var users = User.Factory().MakeMany(3);
var named = User.Factory().Make(new { Name = "Abigail" }); // override attributesAttributes are set by property name; mass-assignment rules ([Fillable]) do not apply. Set(attributes) does the same as a reusable state.
Persisting Models
Create and CreateMany save the models with Save(), so model events, casts such as Hashed, and timestamps apply as usual:
var user = await User.Factory().Create();
var users = await User.Factory().CreateMany(10);
var admins = await User.Factory().Count(3).Set(new { IsAdmin = true }).CreateMany();Sequences
Sequence cycles through values for each model made:
var users = await User.Factory().Count(10)
.Sequence(new { Admin = "Y" }, new { Admin = "N" })
.CreateMany();
var posts = Post.Factory().Sequence(p => p.Title = "First", p => p.Title = "Second").MakeMany(2);Factory Relationships
Belongs To Relationships
For sets the parent on the model's navigation property of that type. Given a factory, it creates one parent and uses it for every model the factory makes; given a model, it uses that model:
var posts = await Post.Factory().For(User.Factory().Set(new { Name = "Jessica" })).CreateMany(3); // one user, three posts
var mine = await Post.Factory().For(user).CreateMany(3);When a model has two navigations of the same type, name one: .For(User.Factory(), p => p.Editor).
Has Many Relationships
Has creates children for each model, on its collection navigation of the children's type:
var user = await User.Factory().Has(Post.Factory().Count(3)).Create();
var authors = await User.Factory().Has(Post.Factory().Count(2)).CreateMany(5); // 5 users with 2 posts eachName the navigation when there are several of that type: .Has(Post.Factory(), u => u.Drafts).
Complete Example: Posts for One Author
After adding the walkthrough's Post model and migration, create:
// database/factories/PostFactory.cs
using Blog.Models;
using DotBlaze;
namespace Blog.Database.Factories;
public class PostFactory : Factory<Post>
{
public override Post Definition() => new()
{
Title = Faker.Lorem.Sentence(),
Body = Faker.Lorem.Paragraph(),
};
}In a test using the complete test-project setup, the following method body creates its own author and checks the foreign keys:
using var app = new DotBlaze.Testing.TestApp<Program>();
await app.RefreshDatabase();
var user = await app.Run(() => Blog.Models.User.Factory().Create());
var posts = await app.Run(() =>
Blog.Models.Post.Factory().For(user).CreateMany(3));
Assert.Equal(3, posts.Count);
Assert.All(posts, post => Assert.Equal(user.Id, post.UserId));
await app.AssertDatabaseCount("posts", 3);For(user) uses Post.User; without it, this factory's UserId remains zero and fails the foreign key when saved. MakeMany does not persist anything. The template's User has no Posts navigation, so add and map an inverse collection before using User.Factory().Has(Post.Factory()).