Skip to content
On this page

测试1:exercises/tests/tests1.rs

题目

rust
// tests1.rs
//
// Tests are important to ensure that your code does what you think it should
// do. Tests can be run on this file with the following command: rustlings run
// tests1
//
// This test has a problem with it -- make the test compile! Make the test pass!
// Make the test fail!
//
// Execute `rustlings hint tests1` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE

#[cfg(test)]
mod tests {
    #[test]
    fn you_can_assert() {
        assert!();
    }
}

测试对于确保代码正确执行非常重要,您可以使用以下命令对此文件运行测试:

bash
rustlings run test1

题目中的测试有问题,先修改代码让单元测试通过编译,让测试通过!

然后再让测试失败。

题目解析

assert! 宏由标准库提供,在希望确保测试中一些条件为 true 时非常有用。需要向 assert! 宏提供一个求值为布尔值的参数。如果值是 trueassert! 什么也不做,同时测试会通过。如果值为 falseassert! 调用 panic! 宏,这会导致测试失败。assert! 宏帮助我们检查代码是否以期望的方式运行。

让测试通过:

rust
#[cfg(test)]
mod tests {
    #[test]
    fn you_can_assert() {
        assert!(); 
        assert!(true); 
    }
}

让测试失败:

rust
#[cfg(test)]
mod tests {
    #[test]
    fn you_can_assert() {
        assert!(); 
        assert!(false); 
    }
}

参考资料

Powered by VitePress