[dev-dependencies] ​

核心概念 ​

[dev-dependencies] 段声明仅在开发阶段使用的依赖,包括单元测试、集成测试、示例程序和基准测试。这些依赖不会被编译进最终的库或可执行文件中,也不会传递给依赖你的 crate 的其他项目。

开发依赖的声明格式与 [dependencies] 完全相同,支持版本号、features、路径、Git 等所有依赖选项。典型的开发依赖包括测试框架、mock 库、临时文件工具、HTTP 客户端(用于集成测试)等。

toml
[dev-dependencies]
# 测试相关
tokio = { version = "1", features = ["test-util", "macros", "rt-multi-thread"] }
pretty_assertions = "1"     # 更好的 assert 输出
proptest = "1"               # 属性测试
mockall = "0.12"             # Mock 框架

# 基准测试
criterion = { version = "0.5", features = ["html_reports"] }

# 工具
tempfile = "3"               # 临时文件
reqwest = { version = "0.12", features = ["json"] }  # HTTP 客户端
wiremock = "0.6"             # HTTP mock 服务器

dev-dependencies vs dependencies ​

特性[dependencies][dev-dependencies]
编译到库/二进制中是否
传递给下游依赖者是否
测试中可用是是
示例中可用是是
基准测试中可用是是
影响发布包大小是否
rust
// dev-dependencies 中的 crate 只能在测试/示例中使用

// 在 #[cfg(test)] 模块中使用
#[cfg(test)]
mod tests {
    // 可以使用 dev-dependencies 中的 crate
    // use pretty_assertions::assert_eq;
    // use tempfile::TempDir;

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

// 在 examples/ 和 tests/ 目录中也可以直接使用
// 但在 src/lib.rs 或 src/main.rs 的非测试代码中不能使用

fn main() {
    println!("dev-dependencies 不会编译进最终产物");
}

常见的开发依赖 ​

toml
[dev-dependencies]
# === 断言增强 ===
pretty_assertions = "1"     # 彩色的 diff 输出
assert_matches = "1.5"      # 模式匹配断言

# === 属性测试 / Fuzzing ===
proptest = "1"               # 自动生成测试数据
quickcheck = "1"             # 随机测试

# === Mock ===
mockall = "0.12"             # 自动生成 mock
wiremock = "0.6"             # HTTP mock

# === 异步测试 ===
tokio = { version = "1", features = ["test-util", "macros", "rt-multi-thread"] }
tokio-test = "0.4"

# === 基准测试 ===
criterion = { version = "0.5", features = ["html_reports"] }
divan = "0.1"

# === 文件和 IO ===
tempfile = "3"               # 临时文件和目录
insta = "1"                  # 快照测试

# === 序列化测试 ===
serde_test = "1"             # serde 序列化测试工具

基本示例 ​

toml
# 项目配置
[package]
name = "my-lib"
version = "0.1.0"
edition = "2024"

[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"

[dev-dependencies]
pretty_assertions = "1"
tempfile = "3"
serde_test = "1"
rust
use serde::{Serialize, Deserialize};

#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct Config {
    pub name: String,
    pub value: i32,
}

impl Config {
    pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
        serde_json::from_str(json)
    }

    pub fn to_json(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string_pretty(self)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    // pretty_assertions 提供更好的 diff 输出
    use pretty_assertions::assert_eq;

    #[test]
    fn test_json_roundtrip() {
        let config = Config {
            name: "test".to_string(),
            value: 42,
        };

        let json = config.to_json().unwrap();
        let parsed = Config::from_json(&json).unwrap();

        // 使用 pretty_assertions 的 assert_eq
        // 失败时会显示彩色的 diff
        assert_eq!(config, parsed);
    }

    #[test]
    fn test_invalid_json() {
        let result = Config::from_json("not json");
        assert!(result.is_err());
    }
}

fn main() {
    let config = Config {
        name: "demo".to_string(),
        value: 100,
    };
    println!("{}", config.to_json().unwrap());
}

常见问题 ​

问题一:dev-dependencies 和 dependencies 中可以有同一个 crate 吗?

可以,但通常是为了在开发阶段启用额外的 features。比如 tokio 在 dependencies 中只启用 rt,在 dev-dependencies 中额外启用 test-util 和 macros。Cargo 会合并两者的 features。

问题二:dev-dependencies 会被下游 crate 编译吗?

不会。当别人 cargo add your-crate 时,你的 dev-dependencies 不会被下载或编译。这是与 dependencies 的关键区别。

问题三:examples/ 目录中可以使用 dev-dependencies 吗?

可以。examples/、tests/、benches/ 目录中的代码都可以使用 dev-dependencies。

问题四:怎么让 dev-dependencies 中的 crate 也能在 src/ 中使用?

不能直接在 src/ 的非测试代码中使用 dev-dependencies。如果需要在库代码中使用,应该放到 [dependencies]。如果只在 #[cfg(test)] 块中使用,dev-dependencies 是可以的。

适用场景 ​

  • 单元测试:断言增强、mock 框架
  • 集成测试:HTTP 客户端、数据库测试工具
  • 基准测试:criterion、divan
  • 快照测试:insta
  • 示例程序:需要的额外工具库

注意事项 ​

  • dev-dependencies 不会编译进最终产物
  • dev-dependencies 不会传递给下游依赖者
  • 与 dependencies 同名 crate 的 features 会被合并
  • 只能在测试、示例、基准测试代码中使用
  • 不影响最终二进制文件的大小

总结 ​

[dev-dependencies] 声明仅在开发阶段使用的依赖,包括测试、示例和基准测试。这些依赖不会编译进最终产物,也不会传递给下游项目。格式与 [dependencies] 完全相同。常见的开发依赖包括 pretty_assertions(更好的断言输出)、criterion(基准测试)、tempfile(临时文件)、mockall(mock 框架)等。同一个 crate 可以同时出现在 dependencies 和 dev-dependencies 中,Cargo 会合并 features。