Rust
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);
}
Exercise 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.
Show example solution
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);
}
Test yourself
-
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
Show answer
Not directly; binary crates can't be imported, the logic must move to lib.rs — This is another reason for the habit of a thin main.rs with the logic in lib.rs.
-
Import the public API
// tests/hesaplar.rs
____ istatistik::ortalama;
Show answer
// tests/hesaplar.rs
use istatistik::ortalama;
-
Test kind and location
- Unit test
- mod tests inside src/
- Integration test
- tests/*.rs
- Shared helper
- tests/ortak/mod.rs
- Doc test
- In /// comments
Next lesson: Doc test