首页 > 解决方案 > 在测试期间忽略部分功能

问题描述

我有一个调用函数的应用程序,该函数最后有一段需要一段时间才能运行的逻辑。我已经独立测试了这个逻辑,因为它是它自己的功能,但它目前使我的测试花费的时间比我希望的要长得多。

有没有一种方法可以让长时间运行的功能在正常使用期间运行,但在我测试hello_world功能时不运行?

锈游乐场

fn main() {
    hello_world();
}

fn hello_world() {
    println!("Hello, world!");

    // Can I ignore this when testing?
    long_running_function();
}

fn long_running_function() {
    for i in 1..100000 {
        println!("{}", i);
    }
}

#[test]
fn hello_world_test() {
    hello_world();
}

标签: rust

解决方案


您可以使用#[cfg(not(test))]

#[cfg(not(test))]
long_running_function();

或宏等价物:

if !cfg!(test) {
    long_running_function();
}

单元测试中的一种常见方法是模拟外部函数,可以提供两个单独的实现,long_running_function具体取决于它是为测试还是目标编译。

#[cfg(not(test))]
fn long_running_function() {
    for i in 1..100000 {
        println!("{}", i);
    }
}

#[cfg(test)]
fn long_running_function() {
    // not so long code
}

否则,您始终可以将布尔值传递给hello_world()并根据该布尔值创建条件。


推荐阅读