expression

Repository pattern: test a service without a database

A small trait can separate a service from its data source. This offline test double answers from a fixed list and lets the service test its branch logic. A real repository contract should retain error information; the bool-only trait here models a deliberately infallible lookup and is not a replacement for database integration tests. No database connection is required by this example. Expected stdout (not executed): service branches checked Common mistake: Assuming an in-memory fake verifies SQL syntax, migrations, constraints or transaction behavior.

Formal Syntax & Structure

rust syntaxrust
trait ItemLookup { async fn exists(&self, id: i32) -> bool; }

Working Example

Example Snippetrust
#[tokio::main(flavor = "current_thread")]async fn main() -> Result<(), Box<dyn std::error::Error>> {    trait ItemLookup { async fn exists(&self, id: i32) -> bool; }    struct Fake([i32; 2]);    impl ItemLookup for Fake {        async fn exists(&self, id: i32) -> bool { self.0.contains(&id) }    }    async fn can_select(repo: &impl ItemLookup, id: i32) -> bool { repo.exists(id).await }    let repo = Fake([1, 2]);    assert!(can_select(&repo, 2).await);    assert!(!can_select(&repo, 9).await);    println!("service branches checked");    Ok(())}
Rust Reference