从货物包裹的测试目录中导入主包装箱

问题描述 投票:0回答:1

我试图看看如何为不在同一文件的模块内的锈可执行文件编写单元测试,而是在货物生成的tests/旁边的src/目录中。目前,这是我的目录设置

hello_cargo
        |
        src
          |
           main.rs
           value.rs
        tests
            |
             tests.rs

价值内容:

#[derive(Debug)]
pub enum Value {
    Int(i32),
    Bool(bool)
}

主要内容

mod value;

use value::Value;

fn main() {
    let x:Value = Value::Int(7);
    let y = Value::Bool(true);

    match x {
        Value::Int(ival) => println!("{}", ival),
        Value::Bool(bval) => println!("{}", bval)
    }

    match y {
        Value::Int(ival) => println!("{}", ival),
        Value::Bool(bval) => println!("{}", bval)
    }
}

test.rs的内容

#[cfg(test)]
mod tests {
    use super::hello_cargo;
    #[test]
    fn it_works() {
        let y = value::Value::Bool(true);
        match y {
            value::Value::Bool(val) => assert!(val),
            _ => ()
        }
    }
}

当我运行cargo test时,我总是得到,有多种不同的use::组合

error[E0432]: unresolved import `super::hello_cargo`
 --> tests/tests.rs:5:6
  |
5 |     use super::hello_cargo;
  |         ^^^^^^^^^^^^^^^^^^ no `hello_cargo` in the root

用可执行文件做不到这个吗?你需要一个库才能在外部测试目录中进行测试吗?

这可以通过将每个文件中的所有代码包装在mod中来解决吗?

rust rust-cargo
1个回答
0
投票

我在tests/目录中找到了下面的代码

use hello_cargo;

// This needs to be in the /tests/ dir beside /src/
// the above `use` must match the name of the crate itself.

#[cfg(test)]
mod tests {
    #[test]
    fn it_works() {
        let y = hello_cargo::value::Value::Bool(true);
        match y {
            hello_cargo::value::Value::Bool(val) => assert!(val),
            _ => ()
        }
    }

}

use语句必须只是当前包生成的包的名称,没有任何superself前缀

© www.soinside.com 2019 - 2024. All rights reserved.