Testing
Unit tests with #[test]
Tests are functions annotated with #[test]. They live in the same file as the code or in a tests module (often behind #[cfg(test)]).
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
}In C#: Like xUnit/NUnit: a method with [Fact] or [Test] that runs as a test. Rust has no separate test runner process by default; cargo test compiles and runs tests.
Running tests
cargo test
cargo test -p course_15_testing
cargo test it_works # run tests whose name contains "it_works"In C#: Like dotnet test; cargo test <name> is like running a single test or filter.
assert! and assert_eq!
assert!(condition)– panics if the condition is false.assert_eq!(left, right)– panics ifleft != right, and prints both values.assert_ne!(left, right)– panics ifleft == right.
In C#: Like Assert.True(condition) and Assert.Equal(expected, actual).
Tests in same file vs tests/ directory
- Same file: Put tests in a
mod tests { ... }with#[cfg(test)]. Good for unit testing private helpers. - tests/ directory: Each
.rsfile undertests/is a separate crate that links your library. Good for integration tests.
In C#: Unit tests next to code vs integration test projects. Rust’s tests/ is like a separate test project that depends on your lib.
Key takeaway
Use #[test] for test functions; run them with cargo test. Use assert!, assert_eq!, and assert_ne! for checks. Use #[cfg(test)] for unit tests in the same crate and tests/ for integration tests.