`

test框架

    博客分类:
  • rust
 
阅读更多
#[derive(Debug)]
struct Rectangle {
    width: u32,
    height: u32,
}

impl Rectangle {
    fn can_hold(&self, other: &Rectangle) -> bool {
        self.width > other.width && self.height > other.height
    }
}

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 }
    }
}

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


//assert!,assert_eq!,assert_ne!
#[cfg(test)] //注解告诉 Rust 仅在您运行时编译和运行测试代码cargo test,而不是在您运行时cargo build
mod tests { //这里似乎同样并不强制这么写
    #[test] //加上这个才能在cargo test中被执行
    fn exploration() {
        let result = 2 + 2;
        assert_eq!(result, 4);
    }

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

    use super::*;

    #[test]
    fn larger_can_hold_smaller() {
        let larger = Rectangle {
            width: 8,
            height: 7,
        };
        let smaller = Rectangle {
            width: 5,
            height: 1,
        };
        assert!(larger.can_hold(&smaller));
    }

    #[test]
    #[should_panic]  //加上这个后失败也不会fail
    fn greater_than_100() {
        println!("test greater_than_100");
        Guess::new(200);
    }

    #[test]
    fn it_works() -> Result<(), String> {
        if 2 + 2 == 4 {
            Ok(())
        } else {
            Err(String::from("two plus two does not equal four"))
        }
    }

    #[test]
    #[ignore] //耗时的可以标记ignore,不批量运行;
    // cargo test -- --ignored 单独运行
    // cargo test -- --include-ignored 运行所有包含ignore的
    fn expensive_test() {
        // code that takes an hour to run
    }

    #[test]
    //测试可以直接调用私有函数
    fn internal() {
        assert_eq!(4, internal_adder(2, 2));
    }
}

cargo test
cargo test -- --show-output //打印输出
cargo test greater //过滤运行

如果要测试tests文件夹某个文件,则:
cargo test --test integration_test

如果要调用某个函数又不想加入测试则在tests文件夹增加一个common目录
mod common;

#[test]
fn it_adds_two() {
    common::setup();
    assert_eq!(4, 2+2);
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics