← Back to Rust Course | Chapter 15: Cargo, Testing & Best Practices | Lesson 5 of 8

Integration Tests

Integration tests check that all the different parts of your program actually work correctly together, from the outside.

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

bash
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

markup
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));
}

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

markup
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"));
}

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

bash
cargo test

⚠️ Run this command in your terminal.

Common Mistakes
  1. Placing integration tests inside src/ instead of the top-level tests/ directory, which Cargo treats differently.
  2. Forgetting integration tests can only call a crate's public API, not its private internal functions.
  3. Assuming a single tests/ file covers everything -- Cargo compiles each file in tests/ as its own separate test binary.
Chapter Summary
  • Integration tests live in a top-level tests/ directory, separate from src/.
  • 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 test runs both unit tests (in src/) and integration tests (in tests/) together by default.
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.