Seeding fixture data
Learn how to seed known test users into app state before each test, why each test gets fresh data, and how fixtures keep tests isolated and repeatable
A test that checks "fetch user 2 returns Ravi" needs a user 2 to exist. A test that checks "creating a user returns id 4" needs three users to exist already. That starting data is called a fixture, and putting it in place before a test runs is called seeding. A seed function builds the data, the test hands it to the app as state, and the test then checks behaviour against rows it knows exactly.
Where This Fits
The previous page showed how an async test gets its runtime. This page gives those tests something realistic to work with. Up to now the test apps in this chapter answered with fixed strings, and there was nothing to look up, create, or count. Real handlers read and write state, and a test of a real handler needs that state to hold known rows before the first request arrives. Seeding is how those rows get there.
Think of a rehearsal room. The actors need chairs, a table, and a door already on stage before the scene starts, or the first line makes no sense. The seed function is the stagehand who sets the room the same way before every rehearsal. The play changes, the room does not.
The Smallest Working Version
The smallest seed is a function that returns a fixed list of users, plus an app that holds that list in shared state and serves it. Create a project with the usual Axum setup, plus serde for the JSON body:
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
http-body-util = "0.1"
The app lives in src/lib.rs. It holds the users in a RwLock wrapped in an Arc, which is the standard way to share mutable data between handlers. A RwLock is a lock that lets many readers read at once but only one writer write at a time. An Arc is a reference-counted pointer that lets several owners share the same value. Together they let every handler reach the same user list safely.
use std::sync::Arc;
use axum::{Json, extract::{Path, State}, http::StatusCode, routing::get, Router};
use serde::{Deserialize, Serialize};
use tokio::sync::RwLock;
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct User {
pub id: i32,
pub name: String,
pub email: String,
pub role: String,
}
pub fn seed_users() -> Vec<User> {
vec![
User { id: 1, name: "Asha".to_string(), email: "asha@example.com".to_string(), role: "admin".to_string() },
User { id: 2, name: "Ravi".to_string(), email: "ravi@example.com".to_string(), role: "user".to_string() },
User { id: 3, name: "Meera".to_string(), email: "meera@example.com".to_string(), role: "user".to_string() },
]
}
#[derive(Debug, Clone)]
pub struct TestState {
pub users: Arc<RwLock<Vec<User>>>,
}
pub fn test_state() -> TestState {
TestState {
users: Arc::new(RwLock::new(seed_users())),
}
}
async fn list_users(State(state): State<TestState>) -> Json<Vec<User>> {
Json(state.users.read().await.clone())
}
async fn get_user(
State(state): State<TestState>,
Path(id): Path<i32>,
) -> Json<User> {
let users = state.users.read().await;
let user = users.iter().find(|user| user.id == id).unwrap().clone();
Json(user)
}
pub fn users_app(state: TestState) -> Router {
Router::new()
.route("/users", get(list_users))
.route("/users/{id}", get(get_user))
.with_state(state)
}
Two details in that file deserve a second look. First, the route path uses {id}, not :id. Axum 0.8 takes the {id} form, and a :id segment makes the router panic when it is built. Second, get_user unwraps the lookup, which would panic on an unknown id. That is fine for this smallest version, where the test only asks for ids that exist, and the richer example below replaces it with a proper 404.
The test file calls test_state() to build fresh state, then checks the seeded rows:
use axum::{body::Body, http::{Request, StatusCode}};
use axum_project::{test_state, users_app};
use http_body_util::BodyExt;
use serde_json::Value;
use tower::ServiceExt;
#[tokio::test]
async fn seeded_users_are_listed() {
let request = Request::builder()
.uri("/users")
.body(Body::empty())
.unwrap();
let response = users_app(test_state()).oneshot(request).await.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let bytes = response.into_body().collect().await.unwrap().to_bytes();
let body: Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(body.as_array().unwrap().len(), 3);
assert_eq!(body[0]["name"], "Asha");
}
#[tokio::test]
async fn seeded_user_is_found_by_id() {
let request = Request::builder()
.uri("/users/2")
.body(Body::empty())
.unwrap();
let response = users_app(test_state()).oneshot(request).await.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let bytes = response.into_body().collect().await.unwrap().to_bytes();
let body: Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(body["email"], "ravi@example.com");
}
Run the tests with:
cargo test --test users_test
Both pass. The first test proves the seed loaded three users. The second proves a known id finds the right row. Every value in the assertions comes straight from seed_users, so if the seed changes, the tests change with it, and nothing is a mystery number.
Working Setup:
If both tests pass, seeding works: the app serves exactly the rows the seed function built, and each test built its own fresh copy. The pattern from here on is always the same: seed function, state builder, app builder, test.
The Pieces, Explained
The seed function, the state builder, and the app builder each have one job, and keeping them apart is what makes the pattern easy to reuse.
seed_users returns plain data, a Vec<User>, with no app involved. It is a pure function: same call, same three users, every time. Because it returns data and not state, a test can call it directly to check what the seed contains, without building an app at all:
use axum_project::seed_users;
#[tokio::test]
async fn seed_function_returns_the_same_three_users_every_time() {
assert_eq!(seed_users().len(), 3);
assert_eq!(seed_users()[1].name, "Ravi");
}
That test needs no attribute work beyond the runtime, and it pins down the seed itself. If someone edits the seed and breaks a dozen other tests, this test names the real cause.
test_state wraps the seed in the shared container the handlers expect. It calls seed_users, puts the result in a RwLock, and wraps that in an Arc. The Arc is what lets the state be cloned into the router while the test keeps its own handle to the same list. Cloning an Arc does not copy the users. It copies the pointer, so the router and the test look at the same list through two handles.
users_app takes the state and returns the router. It does not build state itself. That split is deliberate: a test that wants different data can build state from a different seed and pass it to the same users_app, and the app never knows the difference. The app is a function of its state, and the seed is how the test chooses that state.
The Concept Behind It
A fixture is a known starting point. Without one, a test that creates a user cannot say what id the new user should get, because it does not know how many users already exist. Without one, a test that fetches a user cannot say what name should come back, because it does not know who is stored. The fixture answers both questions before the test starts, so the assertions can be exact instead of vague.
The rule that makes fixtures work is freshness. Each test builds its own state from the seed, uses it, and throws it away. Nothing carries from one test to the next, so no test can pass only because an earlier test left the right rows behind, and no test can fail only because an earlier test deleted them. A test suite where every test starts from the same known state can run in any order, in parallel, and any number of times, and give the same answers. That property is called repeatability, and it is the whole point of seeding.
A Richer Complete Example
The smallest version only reads. A realistic app also writes, and writing is where seeding earns its keep, because the test can predict the result of a write from the seed. Add a create route that assigns the next id, and a proper 404 for unknown ids. The error type here is the shared one from the authentication chapter, with NotFound becoming 404 and ValidationError becoming 422, both with a JSON {"error": ...} body.
use axum::{Json, extract::{Path, State}, http::StatusCode, response::IntoResponse, routing::get, Router};
#[derive(Debug, Deserialize)]
pub struct NewUser {
pub name: String,
pub email: String,
}
async fn create_user(
State(state): State<TestState>,
Json(input): Json<NewUser>,
) -> Result<(StatusCode, Json<User>), AppError> {
if input.name.trim().is_empty() {
return Err(AppError::ValidationError("name must not be empty".to_string()));
}
let mut users = state.users.write().await;
let id = users.iter().map(|user| user.id).max().unwrap_or(0) + 1;
let user = User { id, name: input.name, email: input.email, role: "user".to_string() };
users.push(user.clone());
Ok((StatusCode::CREATED, Json(user)))
}
async fn get_user(
State(state): State<TestState>,
Path(id): Path<i32>,
) -> Result<Json<User>, AppError> {
let users = state.users.read().await;
users
.iter()
.find(|user| user.id == id)
.cloned()
.map(Json)
.ok_or(AppError::NotFound)
}
The create handler takes the write lock, finds the highest id in the seeded list, adds one, and pushes the new user. With three seeded users, the highest id is 3, so the new user gets id 4. That number is predictable only because the seed is known. The test that checks it is a direct statement of the seed plus the rule:
use axum::Router;
use serde_json::json;
async fn call(app: Router, method: &str, uri: &str, body: Option<Value>) -> (StatusCode, Value) {
let request = Request::builder()
.method(method)
.uri(uri)
.header("content-type", "application/json")
.body(Body::from(body.map(|value| value.to_string()).unwrap_or_default()))
.unwrap();
let response = app.oneshot(request).await.unwrap();
let status = response.status();
let bytes = response.into_body().collect().await.unwrap().to_bytes();
let parsed: Value = if bytes.is_empty() { Value::Null } else { serde_json::from_slice(&bytes).unwrap() };
(status, parsed)
}
#[tokio::test]
async fn created_user_gets_the_next_id() {
let (status, body) = call(
users_app(test_state()),
"POST",
"/users",
Some(json!({ "name": "Kiran", "email": "kiran@example.com" })),
)
.await;
assert_eq!(status, StatusCode::CREATED);
assert_eq!(body["id"], json!(4));
assert_eq!(body["role"], json!("user"));
}
#[tokio::test]
async fn unknown_seeded_id_is_404() {
let (status, _) = call(users_app(test_state()), "GET", "/users/99", None).await;
assert_eq!(status, StatusCode::NOT_FOUND);
}
#[tokio::test]
async fn empty_name_is_rejected() {
let (status, body) = call(
users_app(test_state()),
"POST",
"/users",
Some(json!({ "name": " ", "email": "x@example.com" })),
)
.await;
assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY);
assert_eq!(body["error"], json!("name must not be empty"));
}
The call helper is a small test utility that sends a request and returns the status and the parsed JSON body in one pair. It lives in the test file, not in the app, because only tests need it. Every test on this page uses it, and the later pages in this cluster use the same shape.
Seeding a Different Shape Per Test
One seed does not fit every test. A test for the admin route wants an admin user present. A test for an empty list wants no users at all. The pattern handles both, because the seed is just a function that returns data, and a test can build state from any data it likes.
#[tokio::test]
async fn empty_state_lists_no_users() {
let state = TestState {
users: Arc::new(RwLock::new(vec![])),
};
let (status, body) = call(users_app(state), "GET", "/users", None).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(body.as_array().unwrap().len(), 0);
}
#[tokio::test]
async fn first_user_in_empty_state_gets_id_one() {
let state = TestState {
users: Arc::new(RwLock::new(vec![])),
};
let (status, body) = call(
users_app(state),
"POST",
"/users",
Some(json!({ "name": "First", "email": "first@example.com" })),
)
.await;
assert_eq!(status, StatusCode::CREATED);
assert_eq!(body["id"], json!(1));
}
The test builds a TestState by hand with an empty list, instead of calling test_state(). The app does not care, because it only sees state. The second test proves the id rule from the other side: with no rows, the highest id is treated as 0, so the first user gets id 1. Both tests are exact because the starting data is exact.
A second useful variation is to start from the standard seed and change one row. A test that needs a user with a particular email can clone the seed, edit the row, and build state from the edited list. The seed stays the default for every other test, and the one test that needs something special says so in its own body, where the reader can see it.
Seeding Through the API Itself
Sometimes the honest way to set up data is to use the app's own create route, instead of pushing rows into state directly. A test posts a user, checks the create response, and then fetches that user by the returned id. That flow checks two routes at once, and it proves the create route and the fetch route agree with each other.
#[tokio::test]
async fn create_then_fetch_flow() {
let app = users_app(test_state());
let (status, created) = call(
app.clone(),
"POST",
"/users",
Some(json!({ "name": "Kiran", "email": "kiran@example.com" })),
)
.await;
assert_eq!(status, StatusCode::CREATED);
let id = created["id"].as_i64().unwrap();
let uri = format!("/users/{id}");
let (status, fetched) = call(app, "GET", &uri, None).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(fetched["email"], json!("kiran@example.com"));
}
The router is cloned before the first call, because oneshot takes the router by value, and the test needs it again for the second request. Cloning a router is cheap, because the route table is shared behind reference-counted pointers, and the state inside it is the same Arc, so the user created through the first clone is visible to the second. This is the same create-then-fetch shape the database pages of this chapter use, with in-memory state standing in for the database.
Use direct seeding when the test is about one route and the setup is only scaffolding. Use the API flow when the test is about two routes agreeing, or when the setup itself is part of what is being checked. Both are seeding. They differ only in whether the data arrives through the front door or the back door.
Why Fresh State Per Test Is Not Optional
Test A creates user 4
|
v
Shared list now has 4 users
|
v
Test B lists users, expects 3, gets 4
|
v
Test B fails - but only when run after Test A
That diagram is the failure mode of shared fixtures. A test that passes on its own and fails in the full suite is almost always a test that read state another test changed. The fix is the pattern on this page: every test calls test_state() and gets a private list. The proof that the pattern holds is itself a test:
#[tokio::test]
async fn one_test_creating_a_user_does_not_leak_into_another() {
let first = test_state();
let (status, _) = call(
users_app(first),
"POST",
"/users",
Some(json!({ "name": "Kiran", "email": "kiran@example.com" })),
)
.await;
assert_eq!(status, StatusCode::CREATED);
let (_, body) = call(users_app(test_state()), "GET", "/users", None).await;
assert_eq!(body.as_array().unwrap().len(), 3);
}
The first half creates a user in one state. The second half builds a brand new state and lists it. Three users, not four. The new state never saw the create, because it was built from the seed, not from the first state. If this test ever fails, the seed or the state builder has started sharing data between calls, and the failure names the exact problem.
Never Seed Once for the Whole Suite:
A single shared state built once, in a static or in a setup function that runs once, turns every test into a reader of every other test's leftovers. Tests start passing and failing depending on run order, and the failures move when a new test is added. Build state inside each test, from the seed function, every time. The cost is one function call per test, and the saving is a suite that means the same thing on every run.
Common Beginner Mistakes
Random ids in the seed
// Wrong - the seed changes on every run, so no assertion can be exact
pub fn seed_users() -> Vec<User> {
vec![User {
id: rand::random::<i32>(),
name: "Asha".to_string(),
email: "asha@example.com".to_string(),
role: "admin".to_string(),
}]
}
A test cannot assert that fetching user 2 returns Ravi if the seed assigns ids at random. The seed must be fixed and written down, so the tests can name the values they expect. Randomness belongs in property tests that check shapes, not in fixtures that check exact rows. Use fixed ids, fixed names, and fixed emails, and change them only by editing the seed function, where every test can see the change.
Seeding in the app code
// Wrong - production code must not carry test data
pub fn users_app(state: TestState) -> Router {
let mut users = state.users.blocking_write();
if users.is_empty() {
users.extend(seed_users());
}
Router::new().route("/users", get(list_users))
}
Seeding inside the app means the server starts with test users in production, and it means the app behaves differently depending on whether state happened to be empty. The seed belongs in the test setup, in test_state() or in the test file. The app takes state as given and serves it. That split is what lets the same app serve real data in production and seeded data in tests, with no branch in the app code that knows about tests.
Forgetting that the seed and the assertions must agree
A test that asserts body["id"] is 4 only passes while the seed holds exactly three users. If someone adds a fourth user to the seed, that test fails, and the failure is correct: the test and the seed disagreed about the world. The fix is not to make the assertion vague. It is to update the test when the seed changes, or to derive the expected value from the seed in the test itself, by reading seed_users().len() and adding one. Either way, the seed is the single source of truth, and the tests read from it.
Final Complete Example
Everything from this page together: the seed, the state builder, the app with list, fetch, and create, the shared error type, and the test file with the isolation proof:
use std::sync::Arc;
use axum::{Json, extract::{Path, State}, http::StatusCode, response::IntoResponse, response::Response, routing::get, Router};
use serde::{Deserialize, Serialize};
use serde_json::json;
use thiserror::Error;
use tokio::sync::RwLock;
#[derive(Debug, Error)]
pub enum AppError {
#[error("resource not found")]
NotFound,
#[error("{0}")]
ValidationError(String),
#[error("something went wrong")]
InternalError,
#[error("unauthorized")]
Unauthorized,
#[error("forbidden")]
Forbidden,
}
impl IntoResponse for AppError {
fn into_response(self) -> Response {
let status = match &self {
AppError::NotFound => StatusCode::NOT_FOUND,
AppError::ValidationError(_) => StatusCode::UNPROCESSABLE_ENTITY,
AppError::InternalError => StatusCode::INTERNAL_SERVER_ERROR,
AppError::Unauthorized => StatusCode::UNAUTHORIZED,
AppError::Forbidden => StatusCode::FORBIDDEN,
};
let body = Json(json!({ "error": self.to_string() }));
(status, body).into_response()
}
}
pub type HandlerResult<T> = Result<T, AppError>;
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct User {
pub id: i32,
pub name: String,
pub email: String,
pub role: String,
}
pub fn seed_users() -> Vec<User> {
vec![
User { id: 1, name: "Asha".to_string(), email: "asha@example.com".to_string(), role: "admin".to_string() },
User { id: 2, name: "Ravi".to_string(), email: "ravi@example.com".to_string(), role: "user".to_string() },
User { id: 3, name: "Meera".to_string(), email: "meera@example.com".to_string(), role: "user".to_string() },
]
}
#[derive(Debug, Clone)]
pub struct TestState {
pub users: Arc<RwLock<Vec<User>>>,
}
pub fn test_state() -> TestState {
TestState {
users: Arc::new(RwLock::new(seed_users())),
}
}
#[derive(Debug, Deserialize)]
pub struct NewUser {
pub name: String,
pub email: String,
}
async fn list_users(State(state): State<TestState>) -> Json<Vec<User>> {
Json(state.users.read().await.clone())
}
async fn get_user(
State(state): State<TestState>,
Path(id): Path<i32>,
) -> HandlerResult<Json<User>> {
let users = state.users.read().await;
users
.iter()
.find(|user| user.id == id)
.cloned()
.map(Json)
.ok_or(AppError::NotFound)
}
async fn create_user(
State(state): State<TestState>,
Json(input): Json<NewUser>,
) -> HandlerResult<(StatusCode, Json<User>)> {
if input.name.trim().is_empty() {
return Err(AppError::ValidationError("name must not be empty".to_string()));
}
let mut users = state.users.write().await;
let id = users.iter().map(|user| user.id).max().unwrap_or(0) + 1;
let user = User { id, name: input.name, email: input.email, role: "user".to_string() };
users.push(user.clone());
Ok((StatusCode::CREATED, Json(user)))
}
pub fn users_app(state: TestState) -> Router {
Router::new()
.route("/users", get(list_users).post(create_user))
.route("/users/{id}", get(get_user))
.with_state(state)
}
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
thiserror = "2.0"
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
http-body-util = "0.1"
Run the tests with:
cargo test --test users_test
All ten tests pass: the seed pins itself down, the list and fetch tests read it, the create test predicts the next id from it, the 404 and validation tests check the edges, the empty-state tests prove the id rule from zero, the create-then-fetch test checks two routes agreeing, and the isolation test proves one test cannot leak into another.
Summary
A fixture is a promise the test makes to itself: this is the world before the first request. The seed function writes that promise down as data, the state builder wraps it for the app, and each test builds a fresh copy so the promise holds no matter what order the tests run in. The assertions can then be exact, because the starting point is exact, and a failing test points at the handler or at the seed, never at a mystery left behind by another test.
The habit to carry forward is to name the data before writing the test. If a test cannot say what rows exist before it runs, it cannot say what the response should be, and it will end up asserting something vague that passes when it should fail. Seeding fixes that at the source, and the next pages build on it: the login test seeds a user with a known password, and the protected-route tests seed tokens with known claims.