テスト時にのみ有効になる『条件付きコンパイル』について。

単体テスト

test 構成オプションが使える。

なお、この構成オプションはテストモードでのビルド時にのみ有効化される。そのため、結合テストにおいて、テストモードでビルドした tests ディレクトリのコードから、通常モードでビルドした src ディレクトリのコードを実行する場合、src 側のコードにある test は無効化される。

サンプル


pub fn my_func() -> bool {
    #[cfg(test)]
    println!("`my_func` is called.");

    true
}

#[test]
fn test() {
    assert_eq!(my_func(), true);
}

+ 結合テスト

専用のフィーチャーを作り dev-dependencies で適用する。

(dev-dependencies ではそのクレート自身を指定できる。)

サンプル

cargo.toml

[package]
name = "rust_test"
version = "0.1.0"
edition = "2024"

[dev-dependencies]
rust_test = { path = ".", features = ["log"] }

[features]
log = []
src/lib.rs

pub fn my_func() -> bool {
    #[cfg(feature = "log")]
    println!("`my_func` is called.");

    true
}
tests/test.rs

use rust_test::my_func;

#[test]
fn test() {
    assert_eq!(my_func(), true);
}