unit-testing - 为什么我不能运行 main() 中定义的#[test]?

标签 unit-testing rust

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

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

但是,如果我在主函数的外部同时定义加法器函数和测试函数,它就可以工作:

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 测试:

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

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

最佳答案

嵌套测试是不可能的。

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

The problem with this is that the test harness needs to access the inner functions, which it can't do because you can't name them.

在我看来,最好的解决方案是重构您的代码,以便您要测试的方法不再嵌套。

关于unit-testing - 为什么我不能运行 main() 中定义的#[test]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73177482/

相关文章:

unit-testing - 你在哪里设置 OrmLiteConfig.DialectProvider.NamingStrategy 在单元测试中?

javascript - 测试未以 Angular 发出 ajax 请求

unit-testing - 应用服务层 : Unit Tests, 集成测试,还是两者兼而有之?

unit-testing - 我如何对这个用 golang 编写的 promptui 包进行单元测试?

rust - 如何借用一个展开的 Option<T>?

rust - 我如何从图像::ImageBuffer到actix_web::HttpResponse

reactjs - 单元测试功能以检查要调用的调度

generics - 如何要求泛型类型在泛型函数中实现 Add、Sub、Mul 或 Div 等操作?

rust - 如何使包含 Arc 的结构字段可写?

closures - 如何编写一个可以组成 `FnMut` 闭包的函数?