如何找到使用 Cargo 进行测试的资源? [英] How can I locate resources for testing with Cargo?

查看:45
本文介绍了如何找到使用 Cargo 进行测试的资源?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个与文件交互的项目中,我想使用文本文件来测试我的工作.但是测试不是从 tests/ 目录运行的,因此在运行 cargo run 时我无法可靠地找到它们.

I'm on a project interacting with files, and I would like to use text files to test my work. However tests aren't run from the tests/ directory, and thus I cannot reliably find them when running cargo run.

Cargo 是否总是通过从根目录运行测试来处理这个问题(似乎是这种情况,但我没有找到任何证明它的东西)?

Does Cargo handle this by always running test from the root directory (which seems to be the case but I didn't find anything attesting it)?

推荐答案

环境变量 CARGO_MANIFEST_DIR 可以给你一个稳定的基点来引用其他文件.在这里,我们假设在 crate 的顶层有一个 resources/test 目录:

use std::path::PathBuf;

fn main() {
    let mut d = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
    d.push("resources/test");

    println!("{}", d.display());
}

另见:

这篇关于如何找到使用 Cargo 进行测试的资源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆