Provider overrides
Swap a provider for a test double before anything is built from it — what each builder takes, and what the double does to the provider it replaces.
Three builders swap a provider for a double. The override is in place before anything is built, so every consumer injects the double — a singleton service built at boot as much as a controller, a resolver or a guard.
| Builder | Takes | Use when |
|---|---|---|
override_value::<T>(value) | T (owned) | The test does not need to hold the fake — let the container own it |
override_dyn::<T>(Arc<T>) | Arc<dyn Trait> | The provider is registered behind a pub trait |
override_arc::<T>(Arc<T>) | Arc<T> (concrete) | The test still holds the fake to read its state |
struct StubUpstream;
#[async_trait]impl Upstream for StubUpstream { async fn verify(&self, _email: &str) -> Result<Verdict> { Ok(Verdict::Deliverable) }}
let app = TestApp::builder() .module::<ApiModule>() .override_dyn::<dyn Upstream>(Arc::new(StubUpstream)) .build() .await?;When the test needs to observe what the double recorded, keep a handle
to it: build it in an Arc once, hand a clone to the container, and
assert against the shared state after the request. The app binds
HttpUpstream as dyn Upstream, so the double replaces dyn Upstream — the
key UsersService injects — and the Arc<RecordingUpstream> coerces on the
way in:
use std::sync::Arc;
use nest_rs::http::StatusCode;use parking_lot::Mutex;use nest_rs::core::async_trait;
#[derive(Default)]struct RecordingUpstream { asked: Mutex<Vec<String>>,}
impl RecordingUpstream { fn asked(&self) -> Vec<String> { self.asked.lock().clone() }}
#[async_trait]impl Upstream for RecordingUpstream { async fn verify(&self, email: &str) -> Result<Verdict> { self.asked.lock().push(email.to_owned()); Ok(Verdict::Deliverable) }}
#[tokio::test]async fn signup_verifies_the_address_upstream() { let upstream = Arc::new(RecordingUpstream::default()); let app = TestApp::builder() .module::<UsersModule>() .override_dyn::<dyn Upstream>(upstream.clone()) .build() .await .unwrap();
app.http() .post("/users") .body_json(&json!({ "email": "ada@example.com" })) .send() .await .assert_status(StatusCode::CREATED);
assert_eq!(upstream.asked(), vec!["ada@example.com".to_string()]);}override_arc and override_value both replace a concrete provider.
The difference is who keeps the handle: override_value consumes its
argument (you can’t read it back later), override_arc takes a
pre-cloned Arc so the test and the container share the same instance.
What an override does to the provider it replaces
Section titled “What an override does to the provider it replaces”The double stands in for the whole provider:
- The real provider is never built. Its constructor never runs and
its own dependencies need not exist, so a test of
UsersServicecan override its upstream client without wiring what that client would have needed. An overridden factory output — a connection, a config — skips its factory: no connection opens, and the module’s close never runs on the double. - The double keeps the provider’s module. The access graph holds every consumer to the imports production holds it to: a consumer outside the module’s imports fails the boot in the test as it would in production.
- A provider bound
Foo as dyn Traitis overridden whole, through either key. Overridingdyn Traitleaves noFoo, and overridingFooleaves nodyn Trait: a consumer injecting the key left out fails the boot withOverriddenDependencyError, which tells you to override the key that consumer injects. - Its hooks follow the double. A double of the provider’s own type
runs the provider’s
#[hooks],#[scheduled]and kin on itself; one given through the trait object leaves no host for them, so they do not run, and the boot says so atdebug. - A request-scoped or transient provider becomes one double serving every request and every resolution.
- A seed of the same type is replaced, whichever call comes first.
- A duplicate stays a duplicate. A type two modules register, or a
trait object two modules bind, fails the boot with
DuplicateProviderErrorwhether a test overrides it or not.
An override nothing in the app’s graph provides fails the boot with
UnclaimedOverrideError: no module lists the type, no factory or seed
makes it, so the double would never be read. Overriding an edge host
such as a #[controller], which registers routes rather than a value, is
refused the same way.
A seeded config is held to the same ranges and validation as one read
from the environment, before any factory reads it: a test that seeds
HttpConfig { shutdown_timeout: Duration::MAX, .. } fails the boot
naming HttpConfig::shutdown_timeout and its range. So is a config
given through an override, and one seeded on a container built by hand
with Container::builder(), whose build refuses it as
ContainerError::SeedRefused.
External-IO services — HTTP clients to third-party APIs, queue producers
reaching an outside system — are the right override target. The
database is not. A test that mocks Repo to make a service compile is
asserting on a fiction; boot on ephemeral_database instead.
Going further
Section titled “Going further”- End-to-end tests — the boot an override is given to.
- Overriding in tests — a seeded config, and the checks it still passes.
- Providers — scopes, bindings and the access graph an override keeps.