Integration Tests
In this page:
The tests Directory
Cargo recognizes a top-level tests/ directory as the home for integration tests, treating each .rs file inside it as a separate test crate.
Example: The tests Directory
my_project/
src/
lib.rs
tests/
integration_test.rs
⚠️ Run this command in your terminal.
Integration Tests Use the Public API Only
Because each file in tests/ is compiled as its own external crate, it can only call functions the library exposes publicly with pub, just like any other user of the library would.
Example: Integration Tests Use the Public API Only
pub fn add_two(n: i32) -> i32 {
n + 2
}
// In tests/integration_test.rs this would look like:
// use my_project::add_two;
// #[test]
// fn test_add_two() {
// assert_eq!(add_two(3), 5);
// }
fn main() {
println!("add_two(3) = {}", add_two(3));
}
Login to try C/C++/Java/PHP code in the editor
Why Integration Tests Matter
Unit tests verify individual pieces in isolation, while integration tests confirm that those pieces genuinely work together correctly when used the way a real caller would use them.
Example: Why Integration Tests Matter
fn parse_and_double(input: &str) -> Option<i32> {
input.parse::<i32>().ok().map(|n| n * 2)
}
fn main() {
println!("{:?}", parse_and_double("21"));
println!("{:?}", parse_and_double("oops"));
}
Login to try C/C++/Java/PHP code in the editor
Running All Tests Together
cargo test compiles and runs unit tests from src/ alongside every integration test file from tests/, reporting a combined summary of the results.
Example: Running All Tests Together
cargo test
⚠️ Run this command in your terminal.
- Placing integration tests inside
src/instead of the top-leveltests/directory, which Cargo treats differently. - Forgetting integration tests can only call a crate's public API, not its private internal functions.
- Assuming a single
tests/file covers everything -- Cargo compiles each file intests/as its own separate test binary.
- Integration tests live in a top-level
tests/directory, separate fromsrc/. - Each file in
tests/is compiled as an independent crate that can only access the library's public API. - Integration tests verify that multiple parts of a library work correctly together, from an external caller's perspective.
cargo testruns both unit tests (insrc/) and integration tests (intests/) together by default.
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: