TestApp
Replacing a mock, a factory or a whole module in the production graph, and the refusals that keep a stale mock from passing.
A test wants the production application with one part changed: the mailer faked, the clock fixed, a module swapped. TestApp builds the production module graph with those parts replaced and leaves the production modules untouched.
This page follows examples/13-testing.
The application under test
pub trait Mailer: Send + Sync {
fn send(&self, to: &str) -> String;
}
#[module(providers = [SmtpMailer as dyn Mailer], exports = [dyn Mailer])]
pub struct MailModule;
/// Two modules each bind a `Ledger` privately.
pub struct Ledger(pub &'static str);
#[module(providers = [Ledger("billing")], exports = [Ledger])]
pub struct BillingModule;
#[module(providers = [Ledger("refunds")])]
pub struct RefundsModule;
#[module(
imports = [MailModule, BillingModule, RefundsModule],
providers = [with = || Stamp("production".to_owned()), Uptime],
controllers = [SignupController],
)]
pub struct AppModule;Starting one
The test imports TestApp, Dep, StartupError and WiringError from ulo, and Tokio from ulo_runtime_tokio, as examples/13-testing/tests/testing.rs does. App and Connected are also in ulo, and Bound is ulo::app::Bound.
fn test_app() -> TestApp {
TestApp::of(AppModule).runtime(Tokio::current())
}TestApp has the phases AppBuilder has: .wire() and .connect().await. It takes .runtime(..) and .timer(..) too, since the clock is app configuration. connect returns an App<Connected>. To serve it, bind a server on port 0 and serve with no signal, as examples/support does:
pub async fn listen(app: App<Connected>) -> Served {
serve(app.bind(Server::new("127.0.0.1:0")).listen().await.expect("the app listens"))
}
pub fn serve(app: App<Bound>) -> Served {
let addr = app.addresses().first().expect("the app bound an address").addr;
let handle = app.handle();
let task = tokio::spawn(app.serve(std::future::pending()));
Served { addr, handle, task }
}Replacing a value or a factory
let app = test_app()
.override_value::<dyn Mailer>(Arc::new(FakeMailer))
.override_factory(|| async { Stamp("2026-01-01".to_owned()) })
.override_value::<Ledger>(Arc::new(Ledger("test")))
.in_module::<BillingModule>()
.connect()
.await
.unwrap();
let refunds = app.module::<RefundsModule>().unwrap().get::<Ledger>().await.unwrap();
assert_eq!(refunds.0, "refunds", "the scoped override leaves RefundsModule's Ledger alone");
let server = listen(app).await;
assert_eq!(get(server.addr, "/signup").await.body, "fake to ada at 2026-01-01 in test");An override replaces the recipe of an existing key. It keeps the key's origin module, scope, visibility, exports, hooks and readiness check, so the production modules do not change.
| Method | Replaces |
|---|---|
override_value::<T>(Arc<T>) | The binding of T with a value. T may be a trait: dyn Mailer. |
override_factory(|..| async { .. }) | The binding with a closure whose output is the key. Parameters are injection points. |
override_try_factory(..) | The same, for a closure answering a Result. An Err fails connect() with ConnectError::Construct. |
override_many::<T>([..]) | A whole collection. Every production contribution is removed. |
replace_module(Original, Replacement) | A module, by identity. |
override_try_factory and override_many are exercised in crates/ulo/tests/testing.rs.
Matching
An override names no module by default and must match exactly one binding. That is the rule that catches stale mocks.
.in_module::<M>()scopes it to one module. Over several instances ofM, configured or keyed, it is itself ambiguous;.in_module_keyed::<M, Q>()and.in_module_of(&config)name one..everywhere()replaces every match explicitly.- An override targets
T @ (). For a qualified binding,.qualified::<Q>()follows the override:.override_value::<PgPool>(fake).qualified::<Replica>().in_module::<DbModule>(). Inside a keyed module the binding's own key is unqualified, andin_module_keyed::<M, Q>()reaches it as written. - An override cannot change a key's kind.
override_manyreplaces a whole collection and answersTestApp<PendingMany>; its.qualified::<Q>()targets the collectionT @ Q, and it takes no.in_module*, since a collection is app-wide.
let app = TestApp::of(two_dbs()).override_value::<Cfg>(Arc::new(Cfg(9))).everywhere().connect().await.unwrap();
assert_eq!(cfgs(&app).await, (9, 9));That block is from crates/ulo/tests/testing.rs.
Replacing a module
#[module(providers = [FakeMailer as dyn Mailer], exports = [dyn Mailer])]
struct FakeMailModule;
let app = test_app().replace_module(MailModule, FakeMailModule).connect().await.unwrap();The replacement must export a superset of the original's keys, or wiring reports what is missing as ReplacementMissingExports. A replace_module whose original no module imports is ReplacementUnmatched, and a second replacement of one original is DuplicateReplacement naming both calls.
The clock is configuration
TestApp::timer(..) sets the one clock that times the drain, hooks, constructions and readiness checks, and that services read as Dep<dyn Timer>. TestApp::runtime(..) sets the clock and the executor together, which an app that binds a transport needs. Calling .timer(..) after .runtime(..) replaces only the clock, so a test can run a real executor under its own clock.
override_value::<dyn Timer> and override_value::<dyn Runtime> are wiring errors, with the hint "set it with TestApp::timer(..)" or "set it with TestApp::runtime(..)". See Clocks in tests.
What is refused
An override that matches nothing fails wire():
struct Unbound;
let Err(StartupError::Wiring(errors)) = test_app().override_value::<Unbound>(Arc::new(Unbound)).wire() else {
panic!("a stale override should fail wiring");
};
let [WiringError::OverrideUnmatched { key, keyed, at }] = errors.iter().collect::<Vec<_>>()[..] else {
panic!("expected one unmatched override, got {errors}");
};
assert_eq!(key.to_string(), "Unbound");
assert!(errors.to_string().contains("override of `Unbound` matches no binding"), "{errors}");An unscoped override of a key two modules bind lists both:
let Err(StartupError::Wiring(errors)) = test_app().override_value::<Ledger>(Arc::new(Ledger("test"))).wire() else {
panic!("an ambiguous override should fail wiring");
};
let [WiringError::OverrideAmbiguous { key, matches, .. }] = errors.iter().collect::<Vec<_>>()[..] else {
panic!("expected one ambiguous override, got {errors}");
};
let modules: Vec<String> = matches.iter().map(|m| m.to_string()).collect();
assert_eq!(modules, ["BillingModule", "RefundsModule"]);Replacing several by default would make a test pass for the wrong reason, so the ambiguity is an error. .everywhere() is the explicit spelling.
| Mistake | Reported as |
|---|---|
| Override matches no binding | OverrideUnmatched |
Override matches several, .in_module::<M>() over several instances included | OverrideAmbiguous, OverrideModuleAmbiguous |
| Override would change a key from single to collection or back | OverrideKind; the help names override_many |
override_value::<dyn Timer>, override_value::<dyn Runtime> | TimerOverride, RuntimeOverride |
| Replacement lacks an export of the original | ReplacementMissingExports |
| Replaced module is never imported | ReplacementUnmatched |
| One module replaced twice | DuplicateReplacement |
Running the example's tests
cargo test -p ex-13-testing