Is it possible to use Rust's log info for tests?

Viewed 3761

I have some tests which use info! from Rust's log crate. I tried:

RUST_LOG=all cargo test -- --nocapture my_tests

but the logs simply won't come out.

I didn't init the logger though, because puttin env_logger::init(); won't work:

failed to resolve: use of undeclared crate or module `env_logger`
1 Answers

You may try to use one of several workarounds.

First is to use println when crate is compiled for test like this.

#[cfg(not(test))] 
use log::{info, warn}; // Use log crate when building application
 
#[cfg(test)]
use std::{println as info, println as warn}; // Workaround to use prinltn! for logs.

To prevent cargo from silencing tests stdout, run tests like this

$ cargo test -- --nocapture

Another elegant workaround is to use test-env-log crate

#[test_env_log::test] // Automatically wraps test to initialize logging
fn hello_log_tests() {
  // ...
}

To use dependency (such as env_logger mentioned in error message) for tests include it in dev-dependencies section

[dev-dependencies]
env_logger = "*"
Related