1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Rust 単体テスト

Posted at

単体テストのファイル分割

公式ドキュメントによれば、単体テストは、テストされるコードと同じファイルに書くのが基本のよう。
だが、コードが長い場合、テストも長くなりがちなため、ファイルを分けたい場合がある。というか基本全部分けたい。

その際の方法をいくつか調べたのでまとめてみた。

2. src/以下にテスト用のフォルダを作る

my_project/
├── Cargo.toml
└── src/
    ├── main.rs
    ├── my_module.rs
    └── my_module/      <-- my_module.rs に対応するディレクトリを作成
        └── tests.rs    <-- my_module.rs のテストをここに書く

my_module.rsは以下。

// src/my_module.rs

pub fn add(a: i32, b: i32) -> i32 {
    a + b
}
// このように宣言すると、src/my_module/tests.rs を探す
#[cfg(test)]
mod tests;

my_module/tests.rsは以下。

// src/my_module/tests.rs
use super::*; // super は親モジュール(my_module.rs で定義されたモジュール)を指す

#[test]
fn test_add() {
    assert_eq!(add(2, 3), 5);
}

おそらくこの方法が一番見やすい。

方法2. src/以下にテスト用のファイルを作る

my_project/
├── Cargo.toml
└── src/
    ├── main.rs
    ├── my_module.rs
    └── my_module_tests.rs      <-- my_module.rs に対応するファイルを作成

ファイル数が少ないうちは楽だが、テストされるファイルが10を超えると見にくいかな。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?