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

@TestMethodOrder

0
Posted at

🕒 学習時間

17:30~18:00

🧑‍💻 実施した学習内容

1. 疑問点

1.@TestMethodOrderとは何か

2. 技術の概要

◾️何をするものか
JUnit5で「テストメソッドの実行順序」を制御するためのアノテーション

◾️背景・目的(なぜ必要か)
通常、テストは順序に依存しない(独立している)ことが理想です。
しかし現実の開発では以下のケースがある:

  • DBの状態を段階的に確認したい
  • APIの登録→更新→削除の流れをテストしたい
  • 状態遷移のテスト(ステートフルな処理)

このとき、実行順序を明示的に制御する必要がある

◾️ 利用シーン
利用シーン依存関係のあるテスト
→Aのテスト結果を使ってBのテストを行いたい場合。
前処理・後処理
→データのセットアップ、検証、クリーンアップの順序を厳密に定義したい場合。


3. 内容

@TestMethodOrderとは

クラス単位で「テストメソッドの並び順ルール」を指定する

@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class SampleTest {
}

👉 どの順番でテストを実行するかを決める「戦略(Strategy)」を指定している


◾️ MethodOrdererの種類

① OrderAnnotation

  • @Orderの数値で順序制御
  • 小さい順に実行

② MethodName

  • メソッド名の辞書順(アルファベット順)

③ DisplayName

  • @DisplayNameの文字列順

④ Random

  • ランダム順(バグ検出に有効)

⑤ Alphanumeric(※旧)

  • メソッド名+パラメータのアルファベット順
  • 現在は MethodName に統合傾向

4. 用語定義

用語 定義
TestMethodOrder テスト実行順序の戦略指定
MethodOrderer 順序ルールのインターフェース
OrderAnnotation @Order値で制御
DisplayName 表示名
テスト独立性 テスト同士が依存しない設計

5. 解決する課題・メリット

  • テストの順序依存を明示化できる
  • 状態遷移テストが可能
  • バグ再現性が向上
  • ランダム実行で「隠れ依存」を検出できる
  • シナリオテストや統合テストにおいてはこの機能が役立ちます

6. 使用する注意事項・デメリット

❌ アンチパターンになりやすい:

  • テストが順序に依存する = 設計が悪い可能性
  • 並列実行と相性が悪い
  • メンテナンス性低下

👉 原則:
「順序制御は最後の手段」


7. 類似技術との比較

技術 特徴 推奨度
@TestMethodOrder 順序制御 △(限定用途)
@BeforeEach 初期化
@TestInstance(PER_CLASS) 状態共有
DBトランザクションロールバック テスト独立性確保

8. 基本的な使い方・実装(サンプルコード)

OrderAnnotation例

import org.junit.jupiter.api.*;

@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class OrderTest {

    @Test
    @Order(1) // 1番目に実行
    void first() {
        System.out.println("first");
    }

    @Test
    @Order(2) // 2番目に実行
    void second() {
        System.out.println("second");
    }

    @Test
    @Order(3) // 3番目
    void third() {
        System.out.println("third");
    }
}

解説

  • @TestMethodOrderで戦略指定
  • @Orderで順番を明示
  • 数値が小さい順に実行

MethodName例

@TestMethodOrder(MethodOrderer.MethodName.class)
class MethodNameTest {

    @Test
    void testA() {} // 1

    @Test
    void testB() {} // 2

    @Test
    void testC() {} // 3
}

👉 名前順で並ぶ


Random例

@TestMethodOrder(MethodOrderer.Random.class)
class RandomTest {

    @Test
    void test1() {}

    @Test
    void test2() {}

    @Test
    void test3() {}
}

👉 毎回順番が変わる(依存関係の検出に有効)


9. 根拠の掲示

◾️[公式ドキュメント]
https://junit.org/junit5/docs/current/user-guide/#writing-tests-test-execution-order

◾️[参考記事]
https://www.baeldung.com/junit-5-test-order


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