Rust <5>:测试

  测试运行顺序:单元测试(同处于源文件中,以 #[cfg(tests)] 标记 mod,以 #[test] 标记 function)、集成测试(位于项目根路径下的 tests 目录下,不须要 #[cfg(tests)] 标记,但依然须要 #[test] 标记 function)、文档测试。多线程

 

1、选项并发

cargo test [testN] -- --test-threads=1 --nocapture --ignored单元测试

[testN]:能够指定单个测试模块或测试用例的完整名称单独运行,不能批量指定;但能够指定部分名称,全部名称包含此字符串的模块(包含其中全部测试用例)、测试用例均会被执行;测试

--test-threads=1:默认是多线程并发运行测试用例,运行速度快,但会形成输出内容交叉,指定单线程运行可保证有序输出;线程

--nocapture:默认测试经过的用例,其输出内容将会被捕获(屏蔽),指定此选项将会一同显示这些内容;blog

--ignored:被标记为 #[ignore] 的测试用例默认不会被执行,指定此项以运行这些测试用例(一般是预计耗时很长的测试);文档

...字符串

2、单元测试示例it

#[derive(Debug)]
pub struct Rectangle {
    length: u32,
    width: u32,
}

impl Rectangle {
    pub fn can_hold(&self, other: &Rectangle) -> bool {
        return self.length > other.length && self.width > other.width;
    }

    pub fn add_two(&mut self) {
        self.length += 2;
        self.width += 2;
    }
}

#[cfg(test)]
mod should_panic {
    #[test]
    fn notihing() {
        println!("nothing...");
    }

}

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

    #[test]
    fn explotion() {
        assert_eq!(2 + 2, 4);
    }

    #[test]
    fn hellokitty() {
        assert_ne!(1 + 1, 4);
    }

    #[test]
    fn larger_can_hold_smaller() {
        let larger = Rectangle { length: 8, width: 7 };
        let smaller = Rectangle { length: 5, width: 1 };

        assert!(larger.can_hold(&smaller));
    }

    #[test]
    fn smaller_cannot_hold_larger() {
        let larger = Rectangle { length: 8, width: 7 };
        let smaller = Rectangle { length: 5, width: 1 };

        assert!(!smaller.can_hold(&larger));
    }

    #[test]
    #[ignore]
    #[should_panic(expected = "t")]
    fn should_panic() {
        panic! ("test panic");
    }

    #[test]
    fn print_add2() {
        let mut model = Rectangle { length: 8, width: 1 };
        model.add_two();

        assert_eq!(model.length, 10);
    }
}

...io

相关文章
相关标签/搜索