Skip to content
v0.1.1latest release34 skills2 categories4 sub-categories79 tested scripts157 reference docsContact us

Testing Trait Designs

Reference for rust-trait-design-reviewer · 281 lines

Programming / Rustv1.0.0Updated OCT 21 20267 references7 scripts

Traits are seams for tests and promises to implementors. Test both sides: code that uses a trait (with fakes or mocks), and the trait's contract (dyn compatibility, Send/Sync, laws such as Eq/Hash consistency, and what must not compile). Blocks marked rust,ignore need a crate (mockall, proptest, trybuild, static_assertions); the rest compile with std.

Contents

Hand-written fakes

The simplest and most readable test double: a struct implementing the trait with in-memory state. Prefer it when the trait is small and you want to assert on effects rather than on call sequences.

rust
use std::cell::RefCell;
use std::collections::HashMap;

pub trait Store {
    fn get(&self, key: &str) -> Option<String>;
    fn put(&self, key: &str, value: String);
}

pub fn remember_name(store: &dyn Store, user: &str, name: &str) -> bool {
    let key = format!("name:{user}");
    if store.get(&key).is_some() {
        return false;
    }
    store.put(&key, name.to_string());
    true
}

#[derive(Default)]
struct FakeStore {
    data: RefCell<HashMap<String, String>>,
    puts: RefCell<Vec<String>>,          // record calls for assertions
}

impl Store for FakeStore {
    fn get(&self, key: &str) -> Option<String> {
        self.data.borrow().get(key).cloned()
    }
    fn put(&self, key: &str, value: String) {
        self.puts.borrow_mut().push(key.to_string());
        self.data.borrow_mut().insert(key.to_string(), value);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn stores_once() {
        let store = FakeStore::default();
        assert!(remember_name(&store, "u1", "Ada"));
        assert!(!remember_name(&store, "u1", "Bob"));
        assert_eq!(store.puts.borrow().as_slice(), ["name:u1"]);
    }
}

Fakes for generic code work the same way; pass the fake as the type parameter.

mockall

mockall generates a MockTrait with expectations. Useful for checking call counts, argument values and ordering, or for traits with many methods where a fake would be long.

rust
use mockall::{automock, predicate::eq};

#[cfg_attr(test, automock)]
pub trait Clock {
    fn now_ms(&self) -> u64;
}

#[cfg_attr(test, automock)]
pub trait Store {
    fn get(&self, key: &str) -> Option<String>;
}

pub fn is_fresh(clock: &dyn Clock, store: &dyn Store, key: &str) -> bool {
    store.get(key).and_then(|v| v.parse::<u64>().ok()).is_some_and(|t| clock.now_ms() - t < 60_000)
}

#[test]
fn fresh_within_a_minute() {
    let mut clock = MockClock::new();
    clock.expect_now_ms().return_const(100_000u64);
    let mut store = MockStore::new();
    store.expect_get().with(eq("k")).times(1).returning(|_| Some("90000".into()));
    assert!(is_fresh(&clock, &store, "k"));
}

Notes: #[automock] handles generic methods and associated types with some limits; traits with lifetimes in return types may need #[mockall::concretize] or a hand-written fake. Over-specified mocks (exact call order everywhere) make refactoring painful: assert on outcomes where you can.

Compile-time contract checks

Make the contract fail at compile time instead of in a downstream crate:

rust
use std::fmt::Debug;

pub trait Backend: Debug + Send + Sync {
    fn name(&self) -> &str;
}

#[derive(Debug)]
pub struct Memory;
impl Backend for Memory {
    fn name(&self) -> &str { "memory" }
}

// 1. The trait stays dyn compatible (fails with E0038 if someone adds a generic method).
#[allow(dead_code)]
fn assert_dyn_compatible(_: &dyn Backend) {}

// 2. Public types keep their auto traits (removing Send is a breaking change).
const _: () = {
    const fn send_sync<T: Send + Sync>() {}
    send_sync::<Memory>();
    send_sync::<Box<dyn Backend>>();
};

The static_assertions crate offers the same as macros: assert_impl_all!(Memory: Send, Sync, Debug);, assert_not_impl_any!(Guard: Send);, assert_obj_safe!(Backend);.

Things that must not compile

Some promises are negative: a sealed trait cannot be implemented downstream, a guard is not Send, a typestate builder has no build() before url(). Test them with compile_fail doctests (stable, no crates):

rust
/// A typestate builder: `build()` is unavailable until a URL is set.
///
/// ```compile_fail
/// let client = mycrate::Client::builder().build(); // no `build` on ClientBuilder<Missing>
/// ```
///
/// Downstream crates cannot implement the sealed `Codec` trait:
///
/// ```compile_fail
/// struct Mine;
/// impl mycrate::Codec for Mine { fn name(&self) -> &'static str { "mine" } }
/// ```
pub struct Client;

Each compile_fail block should fail for exactly one reason; add the error code (compile_fail,E0599) so a different failure does not pass the test (the code is checked on nightly rustdoc). For many cases, or to pin the exact diagnostic, use trybuild:

rust
#[test]
fn ui() {
    let t = trybuild::TestCases::new();
    t.compile_fail("tests/ui/*.rs"); // each file must fail; stderr compared to tests/ui/*.stderr
}

Regenerate snapshots with TRYBUILD=overwrite cargo test after a compiler update changes wording.

Property tests for trait laws

Some std traits have laws the compiler cannot check. A broken law causes wrong HashMap lookups, unstable sorts or BTreeMap corruption.

Trait(s)Law
PartialEq + Hasha == b implies hash(a) == hash(b)
Eqreflexive, symmetric, transitive
Ord / PartialOrdtotal order consistent with Eq; partial_cmp == Some(cmp)
Borrow<Q>x.borrow() == y.borrow() iff x == y, and hashes agree
Clonex.clone() == x (for PartialEq types)
FromStr + Displays.parse::<T>()?.to_string() == s for canonical strings (round trip)
From<A> for Blossless and infallible; otherwise use TryFrom
rust
use proptest::prelude::*;
use std::hash::{BuildHasher, RandomState};

proptest! {
    #[test]
    fn eq_implies_same_hash(a in "[a-zA-Z]{0,8}", b in "[a-zA-Z]{0,8}") {
        let (ka, kb) = (CaseInsensitiveKey::new(&a), CaseInsensitiveKey::new(&b));
        if ka == kb {
            let s = RandomState::new();
            prop_assert_eq!(s.hash_one(&ka), s.hash_one(&kb));
        }
    }
}

The same check without a crate, for a fixed set of inputs:

rust
use std::collections::hash_map::RandomState;
use std::hash::{BuildHasher, Hash, Hasher};

#[derive(Debug, Clone, Eq)]
pub struct Key(String);

impl PartialEq for Key {
    fn eq(&self, other: &Self) -> bool { self.0.eq_ignore_ascii_case(&other.0) }
}

impl Hash for Key {
    fn hash<H: Hasher>(&self, h: &mut H) {
        self.0.to_ascii_lowercase().hash(h); // hash what eq compares
    }
}

#[test]
fn eq_and_hash_agree() {
    let s = RandomState::new();
    for (a, b) in [("Ab", "aB"), ("x", "X"), ("", "")] {
        let (a, b) = (Key(a.into()), Key(b.into()));
        assert_eq!(a, b);
        assert_eq!(s.hash_one(&a), s.hash_one(&b));
    }
}

Testing default methods and blanket impls

  • Write a minimal test implementor that only provides required methods, then test every default method through it. This catches defaults that accidentally depend on a method an implementor might override.
  • For blanket impls (impl<T: Display> Describe for T), test with a std type, a local type and a reference (&T) to confirm the impl covers what you think.
  • For extension traits, test that the method is available after use crate::prelude::* only (an import test).

Async traits

  • Test async trait users with #[tokio::test] and a fake whose futures complete immediately.
  • Assert the Send promise of an RPITIT method at compile time:
rust
use std::future::Future;

pub trait Fetch: Sync {
    fn fetch(&self, key: &str) -> impl Future<Output = Option<Vec<u8>>> + Send;
}

pub struct Fake;
impl Fetch for Fake {
    async fn fetch(&self, _key: &str) -> Option<Vec<u8>> { Some(vec![1]) }
}

#[allow(dead_code)]
fn assert_send_future<F: Fetch>(f: &F) {
    fn is_send<T: Send>(_: T) {}
    is_send(f.fetch("k")); // fails to compile if an impl's future is not Send
}

Checklist

PromiseTest
Usable as dyn Traitfn _a(_: &dyn Trait) {} in the crate
Public types are Send + Syncconst-fn assertion or static_assertions
Sealed / typestate restrictionscompile_fail doctests or trybuild
Eq/Hash/Ord lawstable test or proptest over generated inputs
Default methods correctminimal implementor + tests per default
Callers behave correctlyhand-written fake (effects) or mockall (interactions)
No accidental API breakcargo semver-checks in CI before publishing
More in Rust

rust-borrow-checker-error-explainer

Explain and fix Rust borrow-checker, ownership, move and lifetime compiler errors: E0382 use of moved value, E0499 cannot borrow as mutable more than once, E0502 also borrowed as immutable, E0505, E0506, E0503, E0507 cannot move out of index/Rc/reference, E0515 return reference to local, E0597 does not live long enough, E0716 temporary value dropped while borrowed, E0373 closure may outlive (spawn needs move), E0521 borrowed data escapes, E0384, E0596, E0594, E0381, E0713, 'lifetime may not live long enough', RefCell 'already borrowed: BorrowMutError' panics. Ranks fixes from restructuring (split borrows, entry API, split_at_mut, get_disjoint_mut, mem::take, Option::take, indices, thread::scope) down to clone and Rc<RefCell>/Arc<Mutex>; never unsafe. Covers NLL limits (get-or-insert), iterator invalidation, closure captures, self-referential structs. Ships std-only Rust triage tools.

rust-cargo-workspace-designer

Design, review and fix Cargo workspaces: when to split a crate (compile time, boundaries, publishing, proc-macros), crates/* vs apps/ + crates/ layouts, virtual manifest vs root package, members/exclude/default-members, resolver 2 vs 3 (MSRV-aware, edition 2024), [workspace.package] and [workspace.dependencies] inheritance, [workspace.lints], root-only profiles (lto, codegen-units), additive features with dep: and weak ?/ syntax, feature unification pitfalls, internal path + version deps, publish = false, Cargo.lock and MSRV policy, xtask, CI with --locked, nextest, rust-cache, sccache, cargo-hack/deny/machete/udeps/semver-checks, and cargo build --timings. Ships a workspace auditor and crate-graph tool.

rust-error-handling-thiserror-anyhow-designer

Design and review Rust error handling with thiserror 2 and anyhow 1: library vs application split, typed error enums with #[from], #[source], #[error(transparent)] and #[non_exhaustive], ErrorKind patterns, context via .context()/.with_context(), bail!/ensure!, source() chains, {:#} and {:?} reports, RUST_BACKTRACE/RUST_LIB_BACKTRACE, Box<dyn Error + Send + Sync>, main -> anyhow::Result or ExitCode, unwrap/expect/panic policy, Option to Result, collecting iterators of Results, axum IntoResponse mapping, retryable errors, tracing, async Send bounds, testing with matches! and downcast_ref, no_std core::error::Error, and snafu, eyre/color-eyre, miette, error-stack.

rust-lifetime-annotation-advisor

Decide when Rust lifetime annotations are needed and which ones: the three elision rules, structs holding references (struct Parser<'a>), owned vs borrowed (String, &str, Cow<'a, str>, Arc<str>), one vs several lifetimes, 'a: 'b bounds, T: 'static misconceptions, Box<dyn Trait + 'a> default object lifetimes, impl Trait + '_ and edition 2024 capture rules with use<..>, variance and PhantomData, HRTB for<'a> Fn(&'a T), GATs and lending iterators, async fn and tokio::spawn 'static, self-referential structs (ouroboros, self_cell, indices, arenas), Rc/Arc to escape lifetime soup. Ships std-only Rust checkers for redundant, missing, unused and over-restrictive lifetimes.

rust-tokio-async-service-builder

Build and review production async Rust services on Tokio 1.x and axum 0.8: runtime choice (#[tokio::main] multi_thread vs current_thread, Builder), axum routing with /{id} paths, State, extractors, IntoResponse error types, axum::serve with_graceful_shutdown, tower/tower-http middleware (TraceLayer, TimeoutLayer, CorsLayer, ConcurrencyLimitLayer, RequestBodyLimitLayer), Arc<AppState>, std vs tokio Mutex, JoinSet, TaskTracker, CancellationToken, select! cancel safety, bounded mpsc, oneshot, broadcast, watch, actors, Semaphore, timeouts, retries, spawn_blocking, sqlx PgPool, reqwest Client reuse, tracing, tests with start_paused and oneshot, Dockerfile. Fixes 'future cannot be sent between threads safely', E0373, Rc or MutexGuard held across await, 'Cannot start a runtime from within a runtime', 'Path segments must not start with :'. Ships std-only Rust scanners and a compiling axum 0.8 scaffold.

rust-unsafe-block-auditor

Audit unsafe Rust for soundness: inventory every unsafe block, unsafe fn, unsafe impl/trait, extern block and unsafe attribute, check // SAFETY: comments and # Safety docs, and classify each as sound, needs-justification or likely UB, proposing safe alternatives first. Covers the five unsafe superpowers, aliasing (Stacked/Tree Borrows), invalid values, MaybeUninit vs mem::zeroed/uninitialized, transmute, slice::from_raw_parts, Vec::set_len/from_raw_parts, get_unchecked, CString::as_ptr dangling, unsafe impl Send/Sync, Pin projection, FFI (extern "C", repr(C), C-unwind, Box::into_raw/from_raw), strict provenance, static mut and &raw, edition 2024 (unsafe extern, #[unsafe(no_mangle)], unsafe_op_in_unsafe_fn, env::set_var), Miri, sanitizers, cargo-fuzz, loom, cargo-geiger and clippy safety lints.