Rust - Basic - 11 - Test

Test

,Rust ,, Test-Driven 。,、,Test-Driven 。Tests,Tests、Tests,。

Compréhension

```rust

pub fn greeting(name: &str) -> String {
    String::from("Hello!")
}

pub struct Guess {
    value: i32,
}

impl Guess {
    pub fn new(value: i32) -> Guess {
        if value < 1 || value > 100 {
            panic!("Guess value must be between 1 and 100, got {}.", value);
        }

        Guess { value }
    }
}

#[cfg(test)]
mod tests {
		use super::*;
    #[test]
    fn it_works() {
				// 也有 assert_ne! 可以使用
        assert_eq!(2 + 2, 4);
    }

		#[test]
    fn will_fail() {
        panic!("Make this test fail");
    }

		#[test]
    fn greeting_contains_name() {
        let result = greeting("Carol");
				// assert 时如果不符合预期,可以 print hint
        assert!(
            result.contains("Carol"),
            "Greeting did not contain name, value was `{}`",
            result
        );
    }
		
		#[test]
		#[should_panic]
		// should_panic 用于检测是否 panic
		fn greater_than_100() {
        Guess::new(200);
    }
}

#[cfg(test)]
mod tests2 {
    #[test]
		// 使用 Result<T, E> 作为retour值,无法使用 should_panic trait
    fn it_works() -> Result<(), String> {
        if 2 + 2 == 4 {
            Ok(())
        } else {
            Err(String::from("two plus two does not equal four"))
        }
    }
}
```

Origin

https://doc.rust-lang.org/book/ch11-00-testing.html