Unit test in Rust

Mattepuffo's logo
Unit test in Rust

Unit test in Rust

Rust ha già praticamente tutto per eseguire unit test.

Basta usare le sue macro.

In questo articolo vediamo qualche esempio.

Tra l'altro dalle ultime versioni è anche possibile fare il test di un Result.

Per semplicità ho messo tutto dentro al main.rs, ma sarebbe il caso di creare un mod apposito:

fn main() {}

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

pub fn is_adult(age: i32) -> Result<i32, String> {
    if age >= 18 {
        Ok(age)
    } else {
        Err("Non sei maggiorenne".to_owned())
    }
}

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

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

    #[test]
    fn test_is_adult() -> Result<(), String> {
        let y = 13;
        assert_eq!(is_adult(y), Ok(y));
        Ok(())
    }

    #[test]
    #[ignore]
    fn test_is_adult_ignore() -> Result<(), String> {
        let y = 13;
        assert_eq!(is_adult(y), Ok(y));
        Ok(())
    }
}

Come vedete è anche possibile ignore un test, come nell'ultimo caso.

Enjoy!


Condividi

Commentami!