Locating resources for testing with cargo

2019-02-13 08:49发布

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.
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)?

1条回答
Explosion°爆炸
2楼-- · 2019-02-13 09:34

I believe that the environment variable CARGO_MANIFEST_DIR can give you a stable base point:

use std::path::PathBuf;

fn main() { }

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

    println!("{:?}", d);
    assert!(false);
}

Some info cribbed from How can a Rust program access metadata from its Cargo package?.

查看更多
登录 后发表回答