CodeBlanks Logo Icon CodeBlanks

Integration test

Write integration tests with the tests/ folder.

Integration tests

Integration tests try the library like a user, only through the public (pub) API. They live in the tests/ folder at the project root, and each file is compiled as a separate crate:

istatistik/
├── Cargo.toml
├── src/lib.rs           // pub fn ortalama(..)
└── tests/
    └── hesaplar.rs

// tests/hesaplar.rs
use istatistik::ortalama;

#[test]
fn ortalama_dogru() {
    assert_eq!(ortalama(&[2.0, 4.0]), 3.0);
}

#[cfg(test)] isn't needed; the tests/ folder is compiled only during cargo test anyway.

Shared test helpers

Setup code used by several test files goes into tests/ortak/mod.rs; if it were tests/ortak.rs, it would count as a test file itself:

// tests/ortak/mod.rs
pub fn ornek_veri() -> Vec<f64> { vec![2.0, 4.0, 9.0] }

// tests/hesaplar.rs
mod ortak;

#[test]
fn uc_degerin_ortalamasi() {
    let v = ortak::ornek_veri();
    assert_eq!(istatistik::ortalama(&v), 5.0);
}

Practice Test from outside

Imitate the library with mod istatistik and write pub fn ortalama(v: &[f64]) -> f64 in it. In main, check assert_eq!(istatistik::ortalama(&[2.0, 4.0]), 3.0) using only the public API, then print ortalama: 3.

Starter code

main.rs
fn main() {
    // buraya yaz
}

Sample solution

main.rs
mod istatistik {
    pub fn ortalama(v: &[f64]) -> f64 {
        v.iter().sum::<f64>() / v.len() as f64
    }
}

fn main() {
    let o = istatistik::ortalama(&[2.0, 4.0]);
    assert_eq!(o, 3.0);
    println!("ortalama: {}", o);
}

Expected output

ortalama: 3

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Can integration tests be written for a package with only <code>src/main.rs</code> (no library)?

  • Yes, use main;
  • Yes, automatically
  • Only unit tests are needed
  • Not directly; binary crates can't be imported, the logic must move to lib.rs Correct answer

Explanation: This is another reason for the habit of a thin main.rs with the logic in lib.rs.

2 Import the public API

Question
// tests/hesaplar.rs
____ istatistik::ortalama;
Answer
// tests/hesaplar.rs
use istatistik::ortalama;

Explanation: Integration tests use the library from outside, by its crate name.

3 Test kind and location

Term Meaning
Unit test mod tests inside src/
Integration test tests/*.rs
Shared helper tests/ortak/mod.rs
Doc test In /// comments

All lessons in Intermediate