Rust - Grundlagen - 11 - Tests

Tests

Insgesamt sind die Testfunktionen von Rust einfach, aber umfassend genug für testgetriebene Entwicklung. Leider sind in meinem Arbeitsumfeld die Ressourcen für Iterationen meist knapp und die Anforderungen zahlreich, sodass sich dieser Ansatz nicht gut eignet. Werden Tests erst später ergänzt, sind Unit- und Integrationstests sehr aufwendig.

Verständnis

  • Grundlegende Syntax

    
    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> 作为返回值,无法使用 should_panic trait
        fn it_works() -> Result<(), String> {
            if 2 + 2 == 4 {
                Ok(())
            } else {
                Err(String::from("two plus two does not equal four"))
            }
        }
    }
    

Quelle

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