3
0

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 3 years have passed since last update.

Rustでテスト(UnitTest)を書く

Posted at

1. はじめに

RustのUnit Testについてクイックスタート的に学んでみようと思います。Rustのドキュメント、Learn Rust/Unit testingを参考にしながらの実践です。Learn Rustにはほかにも、Documentation testingやIntegration testingがありますが、この記事のスコープ外です。

環境情報

この記事は以下の環境で試しています。

  • Windows ver.1903
  • Visual Studio Code 1.49.1
  • 拡張機能①:Rust for Visual Studio Code(0.7.8)
  • 拡張機能②:CodeLLDB(1.5.3)
  • Rust 1.46.0

環境の準備はこちらの記事に書きました。
Visual Studio CodeでRust開発環境を整える

2. Unit Test

ではさっそくUnit Testを書いてみます。

準備

cargo コマンドを利用してクイックスタート用のライブラリパッケージを作成します。

> cargo new adder --lib
     Created library `adder` package

lic.rs を開いてみると、こんなコードになっていてすぐにテストを試すことができます。

lib.rs
# [cfg(test)]
mod tests {
    #[test]
    fn it_works() {
        assert_eq!(2 + 2, 4);
    }
}

では試します。コマンドラインでテストを実行させて結果を確認します。cargo testです。

> cargo test 
   Compiling adder v0.1.0 (D:\Develop\code-writing\rust\adder)
     Running target\debug\deps\adder-251fa9e510f029d1.exe

running 1 test
test tests::it_works ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

   Doc-tests adder

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

実行したところUnit TestとDocumentation Testを2種類のテストが貼りしました。Unit Testは1件passedしていて成功です。

基本的な始め方

テストの基本的な始め方は以下の通り。

  • #[cfg(test)] アトリビュートを付与したtestsモジュールを用意する
  • テストを実行するファンクションには#[test]アトリビュートを付与する

テスト対象の検証方法

テスト対象の検証方法を簡単なコードでまとめます。

lib.rs
# [cfg(test)]
mod tests {
    #[test]
    fn it_works() {
        //値が一致することを検証
        assert_eq!(2 + 2, 4);
    }

    #[test]
    fn it_doesnt_work() {
        //値が一致しないことを検証
        assert_ne!(2 + 2, 5);
    }

    #[test]
    fn it_is_true() {
        //値がtrueであることを検証
        assert!(true);
    }

    // パニックが発生することを検証
    #[test]
    #[should_panic]
    fn test_panic() {
        panic!("hoge-fuga!!");
    }

    // 無視して検証しない
    #[test]
    #[ignore]
    fn ignored_test() {
        //値が一致しないことを検証
        assert_ne!(2 + 2, 5);
    }
}

違和感なくテストが書くことができました。

3.おわりに

Learn Rustを読みながらRustのUnit Testについてまとめてみました。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?