从货物包的测试目录导入主包 crate
Importing the main package crate from the tests directory of a cargo package
我正在尝试查看如何为不在同一文件的模块内的 Rust 可执行文件编写单元测试,而是在 src/
生成的 src/
旁边的 tests/
目录中货物。目前,这是我的目录设置
hello_cargo
|
src
|
main.rs
value.rs
tests
|
tests.rs
value.rs 的内容:
#[derive(Debug)]
pub enum Value {
Int(i32),
Bool(bool)
}
main.rs
的内容
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)
}
}
tests.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
中来解决这个问题?
我在 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
语句必须只是当前包生成的 crate 的名称,没有任何 super
或 self
前缀
我正在尝试查看如何为不在同一文件的模块内的 Rust 可执行文件编写单元测试,而是在 src/
生成的 src/
旁边的 tests/
目录中货物。目前,这是我的目录设置
hello_cargo
|
src
|
main.rs
value.rs
tests
|
tests.rs
value.rs 的内容:
#[derive(Debug)]
pub enum Value {
Int(i32),
Bool(bool)
}
main.rs
的内容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)
}
}
tests.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
中来解决这个问题?
我在 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
语句必须只是当前包生成的 crate 的名称,没有任何 super
或 self
前缀