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

使用Cargo运行Rust集成测试时,如何同步构建cdylib动态库?

解决Cargo运行集成测试时不构建cdylib的问题

有两种实用方法可以让Cargo在运行集成测试时自动构建你的cdylib:

方法一:让测试 crate 显式依赖库(推荐)

因为你的集成测试没有直接引用库,Cargo不会自动触发库的构建。可以通过以下步骤让它识别依赖:

  1. 修改Cargo.toml的[lib]段,同时生成Rust静态库(rlib)和动态库(cdylib):
    [lib]
    crate_type = ["cdylib", "rlib"]
    
  2. 在你的集成测试文件(比如tests/integration.rs)开头添加一行引用,哪怕代码里实际不用这个库:
    use your_crate_name; // 替换成你的 crate 名称
    

这样运行cargo test --test integration时,Cargo会先构建包含cdylib的库,再执行测试。

方法二:手动组合构建与测试命令

如果不想修改crate_type,可以先手动构建库,再运行测试,用一条命令完成:

  • Linux/macOS:
    cargo build --lib && cargo test --test integration
    
  • Windows(PowerShell):
    cargo build --lib; cargo test --test integration
    

这条命令会先确保cdylib被构建,再执行集成测试。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 13:31:09