RRust By Example
intermediateTesting

Unit Tests

Write unit tests with #[test] attribute.

Unit Tests

Write unit tests with #[test] attribute.

Difficulty

Intermediate

Code

rust
fn add(a: i32, b: i32) -> i32 {
    a + b
}

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

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

    #[test]
    fn test_add_negative() {
        assert_eq!(add(-1, 1), 0);
    }

    #[test]
    #[should_panic]
    fn test_panic() {
        panic!("expected panic");
    }
}

fn main() {
    println!("Run with: cargo test");
}

Explanation

Tests use #[test] attribute. Run with cargo test.

Key Concepts

  • Read the code carefully and understand the data flow
  • Try modifying the example to see how it changes behavior
  • Run this code in the Rust Playground

Related Topics

Browse more examples in the testing category to build a complete understanding of this topic.

More Testing Examples