Testing
Unit Testing
- tests module within source code
- auto added when start
cargo new --lib - use
cargo testto see resultscargo testwill build program twice, once without test and once with
- can test private functions by
use super::* #[test]is above individual item- use
#[ignore]to ignore a test #[cfg(test)]is for the module
#[cfg(test)]
mod tests {
// use this line to access private functions
use super::*;
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
#[test]
#[should_panic(expected = "failure message")]
fn pass_when_panic() {
assert_ne!(expression) // pass if not equal
}
#[test]
#[ignore]
fn ignore_for_now() {
assert!(exp,"failure message")
}
// cannot use #[should_panic]
#[test]
fn return_result() -> Result<(), String> {
if 2 + 2 == 4 {
Ok(())
} else {
Err(String::from("some error"))
}
}
}
Integration Tests
- tests module within
testsfolder- all rs in the
testsfolder will be compiled - but not the sub folders, need to be declared
- all rs in the
- does not need
#[cfg(test)]- still need
#[test]
- still need
- also use
cargo testto test - need to have
use crate_nameand only have access to pub fn - only works with
--lib; binary crate cannot usetestsfolder- can use
lib.rsfor logics
- can use
// in `my_test.rs`
use foo;
mod my_other_test;
#[test]
fn some_fn() {
my_other_test::some_fn();
assert!(some_exp);
}
foo
├── Cargo.toml
├── src
│ └── main.rs
│ └── lib.rs
└── tests
├── my_test.rs
└── my_other_test
└── mod.rs