miércoles, 10 de enero de 2024

Unit Tests en Rust


Rust y Cargo vienen con un framework de prueba unitario simple:

  • Las pruebas unitarias son compatibles con todo el código.
  • Las pruebas de integración se admiten a través del directorio tests/.

Las pruebas están anotadas con el atributo #[prueba]. Las pruebas unitarias a menudo se colocan en un módulo de pruebas anidadas, usando #[cfg(test)] para compilarlas condicionalmente. Veamos un ejemplo: 


fn first_word(text: &str) -> &str {

    match text.find(' ') {

        Some(idx) => &text[..idx],

        None => &text,

    }

}


#[cfg(test)]

mod test {

    use super::*;


    #[test]

    fn test_empty() {

        assert_eq!(first_word(""), "");

    }


    #[test]

    fn test_single_word() {

        assert_eq!(first_word("Hello"), "Hello");

    }


    #[test]

    fn test_multiple_words() {

        assert_eq!(first_word("Hello World"), "Hello");

    }

}

Podemos correr los test con cargo test: 


$ cargo test 

   Compiling hello_cargo v0.1.0 

    Finished test [unoptimized + debuginfo] target(s) in 0.37s

     Running unittests src/main.rs 


running 3 tests

test test::test_multiple_words ... ok

test test::test_empty ... ok

test test::test_single_word ... ok


test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s



No hay comentarios.:

Publicar un comentario