expression
Database integration tests: assert constraint behavior
An integration test should inspect the kind of database failure, not just whether an operation failed. A duplicate primary key must fail because of a uniqueness rule, not because the table is missing. This sample checks SQLite, not MySQL or PostgreSQL error behavior. Uses a disposable in-memory SQLite database, with no external database. Expected stdout (not executed): unique violation: true Common mistake: Accepting every error as proof a constraint works.
Formal Syntax & Structure
rust syntaxrust
assert!(error.as_database_error().is_some_and(|e| e.is_unique_violation()))Working Example
Example Snippetrust
#[tokio::main(flavor = "current_thread")]async fn main() -> Result<(), Box<dyn std::error::Error>> { let pool = sqlx::sqlite::SqlitePoolOptions::new().max_connections(1).connect("sqlite::memory:").await?; sqlx::query("CREATE TABLE items (id INTEGER PRIMARY KEY)").execute(&pool).await?; sqlx::query("INSERT INTO items VALUES (1)").execute(&pool).await?; let error = sqlx::query("INSERT INTO items VALUES (1)").execute(&pool).await.unwrap_err(); let unique = error.as_database_error().is_some_and(|e| e.is_unique_violation()); assert!(unique); println!("unique violation: {unique}"); pool.close().await; Ok(())}