Integration Testing Implementation in Rust
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Integration Testing runs in O(n) time and O(n) space, in Rust as in every other language.
- ✓There is no framework beyond the built-in harness: #[test], assert_eq!, #[should_panic]. Files under tests/ are compiled as separate integration crates that can only see your crate's public API, which is the structural difference from #[cfg(test)] unit tests.
- ✓Reviewers want resources owned by a guard whose Drop does the cleanup, tests that return Result<(), sqlx::Error> and use ?
- ✓The Rust trap: Each #[tokio::test] builds its own runtime and DROPS it when the test returns. Anything you cached in a OnceLock or OnceCell, a pool or a spawned background task, belongs to the first test's runtime; once that runtime is dropped its workers and IO driver go with it, and the next test hangs or panics about a Tokio context that is shutting down.
- ✓cargo test builds one binary per file in tests/, so link time, not run time, dominates; a dozen tiny integration files cost far more than one file holding a dozen tests.
What Integration Testing actually is
Integration Testing in Rust: what you actually reach for
Rust implementation
use sqlx::PgPool;
#[derive(Debug, Clone)]
struct NewOrder {
sku: String,
qty: i32,
}
impl Default for NewOrder {
fn default() -> Self {
Self { sku: "ABC-1".to_string(), qty: 1 }
}
}
// #[sqlx::test] creates a fresh database, runs ./migrations, drops it after.
#[sqlx::test]
async fn insert_then_read_back(pool: PgPool) -> sqlx::Result<()> {
let order = NewOrder { qty: 3, ..Default::default() };
let id: i64 = sqlx::query_scalar(
"INSERT INTO orders (sku, qty) VALUES ($1, $2) RETURNING id",
)
.bind(&order.sku)
.bind(order.qty)
.fetch_one(&pool)
.await?;
let qty: i32 = sqlx::query_scalar("SELECT qty FROM orders WHERE id = $1")
.bind(id)
.fetch_one(&pool)
.await?;
assert_eq!(qty, 3);
Ok(())
}
Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Rust-specific trap
Performance in Rust, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Rust type or library should I use for Integration Testing?
There is no framework beyond the built-in harness: #[test], assert_eq!, #[should_panic]. Files under tests/ are compiled as separate integration crates that can only see your crate's public API, which is the structural difference from #[cfg(test)] unit tests. Async needs an attribute, #[tokio::test], with tokio's rt and macros features. For databases, sqlx's #[sqlx::test] provisions a fresh database per test, applies ./migrations, injects a PgPool argument and drops the database afterwards; the testcontainers crate covers everything sqlx does not. HTTP tests use reqwest against an axum or actix app bound to port 0.
What is the most common Rust mistake when implementing Integration Testing?
Each #[tokio::test] builds its own runtime and DROPS it when the test returns. Anything you cached in a OnceLock or OnceCell, a pool or a spawned background task, belongs to the first test's runtime; once that runtime is dropped its workers and IO driver go with it, and the next test hangs or panics about a Tokio context that is shutting down. Separately, #[tokio::test] defaults to a current-thread runtime, so code that assumes multi-threaded scheduling needs flavor = "multi_thread". And a container guard's Drop is not unconditional: under the default unwinding strategy the harness catches the panic on that test's own thread, so its locals including the guard do drop and the sibling tests finish, but nothing drops under panic = "abort", a second panic during unwinding, process::exit, or a CI timeout that kills the binary, and those containers are orphaned.
How does Integration Testing actually perform in Rust?
cargo test builds one binary per file in tests/, so link time, not run time, dominates; a dozen tiny integration files cost far more than one file holding a dozen tests. Inside a binary the harness runs tests on as many threads as there are cores, so a create-database-per-test strategy means that many concurrent databases. Creating a database and running migrations is tens of milliseconds against a warm local server, against sub-millisecond for a ROLLBACK. cargo-nextest gives one process per test, buying isolation at the cost of a process spawn each time. Time complexity is O(n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialBefore paying for Replit, check its student and free-tier options on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.