Skip to main content

How to set up a Rust project with Cargo and tests

Set up a Rust project with Cargo: create the project, add crates with cargo add, write unit tests in a cfg(test) module and integration tests in tests/, then run cargo test.

Difficulty
Beginner
Duration
35 minutes
Steps
6

What Cargo is

Cargo is Rust's build system and package manager. It creates projects, resolves and downloads dependencies (crates) from crates.io, compiles code, and runs tests, all through one tool. Rust's testing support is built in: tests live alongside code and run with a single command.

Prerequisites

  • Rust and Cargo installed via rustup
  • A terminal

Steps

1. Create a project with Cargo

cargo new calc --lib
cd calc

This creates Cargo.toml and a src/lib.rs.

2. Add a dependency

Add crates with cargo add, which edits Cargo.toml for you.

cargo add rand

3. Write code to test

pub fn add(a: i64, b: i64) -> i64 {
    a + b
}

4. Add unit tests

Unit tests live in the same file inside a #[cfg(test)] module so they can access private items.

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn adds_two_numbers() {
        assert_eq!(add(2, 3), 5);
    }
}

5. Add an integration test

Integration tests live in a top-level tests/ directory and use the crate as an external user would.

// tests/api.rs
use calc::add;

#[test]
fn public_api_works() {
    assert_eq!(add(10, 5), 15);
}

6. Run tests and build a release

cargo test
cargo build --release

cargo test compiles and runs both unit and integration tests.

Verification

Run cargo test and confirm all tests pass. Change an assertion to a wrong value and confirm Cargo reports the failure with the expected and actual values. Run cargo clippy to catch common issues.

Next Steps

Add documentation tests in /// comments, set up cargo fmt, measure coverage, and run cargo test in continuous integration.

Prerequisites

  • Rust and Cargo installed
  • Basic command line familiarity

Steps

  • 1
    Create a project with Cargo
  • 2
    Add a dependency
  • 3
    Write code to test
  • 4
    Add unit tests
  • 5
    Add an integration test
  • 6
    Run tests and build a release