You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rust测试场景下如何从main访问module2中builder.rs的函数

解决步骤

1. 将module2加入Cargo工作区

修改根目录的Cargo.toml,把module2添加到workspace.members列表中:

[workspace]
members = ["main", "module2"]

2. 在main项目中添加module2的开发依赖

修改main/Cargo.toml,在[dev-dependencies]下添加module2的路径依赖(仅测试环境需要时用此配置):

[dev-dependencies]
module2 = { path = "../module2" }

如果主代码也需要调用module2的功能,将依赖配置到[dependencies]下即可。

3. 确保module2的代码可被外部访问

  • 在module2/src/lib.rs中导出builder模块:
pub mod builder;
  • 在module2/src/builder.rs中,把需要被调用的函数标记为公开(pub):
pub fn build() {
    // 你的函数逻辑
}

4. 在main的测试代码中正确导入使用

在main/src/main.rs的测试块中,按如下方式导入调用:

#[cfg(test)]
mod tests {
    use module2::builder::build;

    #[test]
    fn test_build() {
        build();
        // 测试逻辑
    }
}

完成以上步骤后,重新运行cargo test即可正常访问builder.rs里的函数。

内容的提问来源于stack exchange,提问作者Szegoo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 22:36:19