如何为集成测试初始化​​记录器? [英] How to initialize the logger for integration tests?

查看:24
本文介绍了如何为集成测试初始化​​记录器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 src 目录中有一个带有生产代码的 crate,在 tests 目录中有集成测试.生产代码使用 log 宏.

I have a crate with production code in the src directory and integration tests in the tests directory. The production code uses log macros.

我想在运行集成测试时初始化一个全局记录器(例如 env_logger::init().unwrap();)有几个测试,没有定义测试顺序,所以我不知道我应该把初始化命令放在哪个测试中.

I would like to init a global logger when running the integration tests (e.g. env_logger::init().unwrap();) There are several tests and the test order is not defined, so I don't know in which test I should put the initialize command.

有什么办法可以很好地做到这一点吗?也许通过覆盖测试 main 函数?

Is there any way I can do this nicely? Perhaps by overriding the tests main function?

推荐答案

你可以这样使用:

use std::sync::Once;

static INIT: Once = Once::new();

/// Setup function that is only run once, even if called multiple times.
fn setup() {
    INIT.call_once(|| {
        env_logger::init().unwrap();
    });
}

然后在每次测试开始时简单地调用 setup().

Then simply call setup() in the beginning of each test.

最初基于这篇博文.

这篇关于如何为集成测试初始化​​记录器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆