5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

現在フリーランスエンジニアとして活動していて、今今携わっている案件ではRustとTauriを使ってExcelファイルを出力するデスクトップアプリを開発しています。

上記デスクトップアプリにはユーティリティ関数としてアラビア数字を漢数字に変換する関数があり、テストを実装しようとすると似たようなテストケースが増えて多少保守性が悪くなるので、今回パラメタライズドテストで実装したいと思います。

Rustでパラメタライズドテストを実装しようとすると方法としてはマクロを使う方法やtest-caseクレートやrstestクレートを使う方法があります。自分が元々Pythonとpytestを使っていて、rstestが作者曰くpytestの構文を模倣して似ているということなのでrstestを使いたいと思います。

Cargo.toml
[dev-dependencies]
rstest = "0.17.0"

早速、上記クレートを使用したパラメタライズドテストのサンプルコードを載せます。

#[cfg(test)]
mod tests {
    use rstest::rstest;

    use super::*;

    #[rstest]
    #[case(1, "一")]
    #[case(31, "三十一")]
    #[case(12345, "一万二千三百四十五")]
    #[case(100000, "十万")]
    #[case(1000000, "百万")]
    fn test_to_kanji(#[case] n: u32, #[case] expected: String) {
        assert_eq!(to_kanji(n), expected)
    }
}

#[test]の代わりにrstestアトリビュートを使用し、複数の#[case]アトリビュートを使ってテストケースを定義しています。そして、それぞれの#[case]アトリビュートでは、テストの対象関数に渡す引数の値を指定し、テスト関数の引数にも#[case]アトリビュートをつけて引数を渡します。

上記のテスト関数test_to_kanjiには漢数字に変換したい数値であるnと期待する漢数字の文字列であるexpectedの2個の引数があり、assert_eq!マクロを使って期待する結果と実際の結果を比較しています。

cargo testで上記のテスト関数を実行すると、

test utils::tests::test_should_return_kanji_number_for_to_kanji::case_1 ... ok
test utils::tests::test_should_return_kanji_number_for_to_kanji::case_2 ... ok
test utils::tests::test_should_return_kanji_number_for_to_kanji::case_3 ... ok
test utils::tests::test_should_return_kanji_number_for_to_kanji::case_4 ... ok
test utils::tests::test_should_return_kanji_number_for_to_kanji::case_5 ... ok
test utils::tests::test_should_return_kanji_number_for_to_kanji::case_6 ... ok

となり、それぞれのテストケースごとにテスト結果を表示します。

以上でRustでも簡単にパラメタライズドテストを実装することができました。rstestには上記以外にもfixtureなど便利な機能もあるようなのでもっと使い方を勉強したいと思います。

5
3
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
5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?