单元测试
Rust 和 Cargo 随附了一个简单的单元测试框架:
- 单元测试在您的整个代码中都受支持。
- 您可以通过
tests/目录来支持集成测试。
Tests are marked with #[test]. Unit tests are often put in a nested tests module, using #[cfg(test)] to conditionally compile them only when building tests.
1. fn first_word(text: &str) -> &str {
2. match text.find(' ') {
3. Some(idx) => &text[..idx],
4. None => &text,
5. }
6. }
8. #[cfg(test)]
9. mod tests {
10. use super::*;
12. #[test]
13. fn test_empty() {
14. assert_eq!(first_word(""), "");
15. }
17. #[test]
18. fn test_single_word() {
19. assert_eq!(first_word("Hello"), "Hello");
20. }
22. #[test]
23. fn test_multiple_words() {
24. assert_eq!(first_word("Hello World"), "Hello");
25. }
26. }
- 这样一来,您可以对专用帮助程序进行单元测试。
- 仅当您运行
cargo test时,#[cfg(test)]属性才有效。
This slide should take about 5 minutes.
在 Playground 中运行测试显示测试结果。
