【Rust】使用 Rust 语言实践完整的 TDD(测试驱动开发)流程

写个简单的TDD练练手。

需求描述

我们要实现一个简单的功能:计算两个整数的和。

步骤 1:编写失败的测试用例

首先,创建一个新的 Rust 项目,并用 VS Code 打开:

bash 复制代码
cargo new test_tdd --lib
cd .\test_tdd\
code .

默认的库文件里包含了一个加法的实现,这里直接把实现改成报错:

rust 复制代码
pub fn add(left: usize, right: usize) -> usize {
    // left + right
    unimplemented!()
}

如果你没有,那我把完整的代码贴出来:

rust 复制代码
pub fn add(left: usize, right: usize) -> usize {
    // left + right
    unimplemented!()
}

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

    #[test]
    fn it_works() {
        let result = add(2, 2);
        assert_eq!(result, 4);
    }
}

运行测试:

bash 复制代码
cargo test

不出意外,测试失败了:

步骤 2:编写代码使测试通过

修改add函数的实现,让测试能够通过。

rust 复制代码
pub fn add(left: usize, right: usize) -> usize {
    left + right
}

步骤 3:重构代码

此处无需重构了,足够简洁。

相关推荐
wflynn18 小时前
GitHub 今日推荐|Stela:在 PC 上直接启动 macOS 的翻译层
rust·开源·github
aifannihao20 小时前
Rust 1.100 的 DropGuard:用 Python 实测失败回滚与吞异常
python·rust·异常处理·标准库·contextlib
鶴哥只手遮天1 天前
《rustc 内幕》第 1 章 全景:rustc 编译流水线与 crate 版图
后端·rust·开源
SomeOtherTime2 天前
Rust 闭包语法和原理(AI回答)
开发语言·后端·rust
SomeOtherTime2 天前
Rust集合(AI回答)
开发语言·后端·rust
SomeOtherTime3 天前
Rust 泛型与特性讲解(AI回答)
rust
青川Lapis3 天前
RUST:错误处理 thiserror + anyhow 工程化
rust
SomeOtherTime3 天前
Rust生命周期介绍(AI回答)
开发语言·后端·rust
SomeOtherTime4 天前
Rust所有权(AI回答)
开发语言·后端·rust
SomeOtherTime4 天前
Rust 面向对象介绍(AI回答)
开发语言·python·rust