我正在学习Rust,我想在main中测试一个简单的函数.rs as:

fn main() {
    fn adder(n: u64, m:u64) -> u64 {
        assert!(n != 0 && m !=0);
        n + m
    }

    #[test]
    fn test_gcd(){
        assert_eq!(adder(1, 10), 11);
        assert_eq!(adder(100, 33), 133);
    }
    println!("{}", adder(3, 4));
    println!("The END");
}

当我运行cargo test时,未找到任何测试,并显示此警告:

warning: cannot test inner items
 --> src\main.rs:7:5
  |
7 |     #[test]
  |     ^^^^^^^
  |
  = note: `#[warn(unnameable_test_items)]` on by default
  = note: this warning originates in the attribute macro `test` (in Nightly builds, run with -Z macro-backtrace for more info)

warning: `rust_prueba` (bin "rust_prueba" test) generated 1 warning
    Finished test [unoptimized + debuginfo] target(s) in 0.58s
     Running unittests src\main.rs (target\debug\deps\rust_prueba-e1ba8a7bcfb64cfc.exe)

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

但是,如果我同时定义加法器函数和测试函数outside作为主函数,它可以工作:

fn main() {
    println!("{}", adder(3, 4));
    println!("The END");
}

fn adder(n: u64, m:u64) -> u64 {
    assert!(n != 0 && m !=0);
    n + m
}

#[test]
fn test_gcd(){
    assert_eq!(adder(1, 10), 11);
    assert_eq!(adder(100, 33), 133);
}

cargo test:

running 1 test
test test_gcd ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

为什么我的第一次try 没有成功?

推荐答案

不可能进行嵌套测试.

request to add that个,但结果是这是不可能实现的:

问题是测试线束需要访问内部函数,但它无法访问,因为您无法命名它们.

在我看来,最好的解决方案是重新构造代码,使要测试的方法不再嵌套.

Rust相关问答推荐

基于对vec值的引用从该值中删除该值

trait声明中的生命周期参数

如何在Rust中表示仅具有特定大小的数组

Box::new()会从一个堆栈复制到另一个堆吗?

像这样的铁 rust 图案除了‘选项’之外,还有其他 Select 吗?

S,一般性状和联想型性状有什么不同?

取得本地对象字段的所有权

重写Rust中的方法以使用`&;mut self`而不是`mut self`

在我的Cargo 中,当我在建筑物中使用时,找不到我可以在产品包中使用的 crate .r我如何解决这个问题?

如何防止Cargo 单据和Cargo 出口发布( crate )项目

在Rust中克隆源自INTO_ITER()的迭代器的成本?

如何设置activx websocket actorless的消息大小限制?

全面的 Rust Ch.16.2 - 使用捕获和 const 表达式的 struct 模式匹配

为什么不能在 Rust 中声明静态或常量 std::path::Path 对象?

在给定 Rust 谓词的情况下,将 Some 转换为 None 的惯用方法是什么?

特征中定义的类型与一般定义的类型之间的区别

Rust 将特性传递给依赖项

为什么会出现无法移出可变引用后面的 `self.x`错误?

Iterator::collect如何进行转换?

为什么 `ref` 会导致此示例*取消引用*一个字段?