unit-testing - 在 Rust 测试中使用外部文件

标签 unit-testing rust

我正在编写一个从文件中读取文件内容的服务,该位置是从环境变量中读取的 FILE_LOCATION .

fn my_function(){
    let path = match env::var("FILE_LOCATION") {
    ...
    let contents = match fs::read(&path) {
}


我有一个测试文件 test_file.json在:
proj
  resources
    test
      test_file.json
  src
    main.rs
  tests
    unit_tests.rs


在测试中我可以设置 FILE_LOCATION :
env::set_var("FILE_LOCATION", "path/to/test/file");

问题是 path/to/test/file 的值应该是多少?

或者换句话说:

如何在 Rust 测试中访问外部文件?

最佳答案

Cargo 设置环境变量 CARGO_MANIFEST_DIR到包含您的 Cargo.toml 的目录文件。所以你可以得到那个环境变量,并附加 resources/test/test_file.json到它。

https://doc.rust-lang.org/cargo/reference/environment-variables.html Cargo 设置什么环境变量。

关于unit-testing - 在 Rust 测试中使用外部文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59586527/

相关文章:

python - 我的单元测试中可以包含哪些附加测试用例?

rust - 对于列出为实现的类型,未实现IntoHandlerError

rust - 返回结果::Err()导致E0308及其堵塞我的错误日志

rust - 我怎样才能延长结构的生命周期,以便我可以用它调用 tokio::run?

java - 伪造 Ajax 请求表单以进行测试

C# - 原型(prototype)设计时的 TDD 策略

c# - 单元测试接口(interface)与最小起订量

php - 在单个测试中断言多个条件,还是拆分为多个测试?

methods - 一个 Rust 类型之谜 : Convert a function to a method, 和调用函数的签名破坏了编译

Rust:如何指定一种可能的返回类型?