Mr.Smithyyy
Mr.Smithyyy

Reputation: 1329

Ignore part of function during tests

I have an application that calls a function that, at the end, has a piece of logic that takes a while to run. I already test this logic independently since it is it's own function but it currently makes my tests take much longer than I would like them to.

Is there a way I can make the long running function run during normal usage but not when I'm testing the hello_world function?

Rust Playground

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();
}

Upvotes: 1

Views: 812

Answers (1)

Nathanael Demacon
Nathanael Demacon

Reputation: 1217

You can use #[cfg(not(test))]:

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

Or the macro equivalent:

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

A common approach in unit-testing is to mock external functions, it is possible to provide two separate implementations of long_running_function depending if it is compiled for test or target.

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

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

Else you can always pass a boolean to hello_world() and make a condition based on this boolean.

Upvotes: 3

Related Questions