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

呼び出しメソッドに渡す引数をJunitで確認する方法

Last updated at Posted at 2018-11-17

目的

  • PG内でメソッドを呼び出しを行うが、そこに渡している引数を想定通り渡せているか確認を行う
    • メソッドの返り値が画像等、Junitでの検証が行いにくい場合に想定通りに引数を渡せているかで検証を行う
  • Mock化したクラス・メソッドに渡した引数で返り値を制御したい

環境準備

Mavenの場合
以下タグを<dependencies>の配下に追加

        <dependency>
            <groupId>org.jmockit</groupId>
            <artifactId>jmockit</artifactId>
            <version>1.8</version>
            <scope>test</scope>
        </dependency>

Mock化手順

今回は例として、Randon#nextInt(int)をモック化します。

Test対象クラス

    public int  getRandomName(int min, int max){
        return new Random().nextInt(max-min) + min;
    }

実際のチェック実装


     final int max;
     final int min;
     //RandomをMock化
     MockUp<Random> mocked = new MockUp<Random>(){
        @Setter 
        private int expectedArg;
        /**
         * {@link Random#nextInt} に想定した引数を指定しているか確認.
         */
        @Mock
        public int nextInt(int argMax) {
            //引数チェック
            assertEquals("引数チェック",expectedArg,argMax);
            //モックとしては最大値を返却
            return argMax;
        }
    };

Test実行

ここでgetRandomName(int,int)を呼び出した際に中でモック化されたRandon#nextInt(int)が呼び出される。(引数チェックも合わせて実施される)

//想定値をモックに指定
mocked.setExpectedArg(8);
//実際のテスト対象メソッド呼び出し
new TestTargetClass().getRandomName(2,10);

Test完了後

忘れずにtearDown()を呼び出す
後続の無関係のテストにも影響する可能性があるので、忘れずに後処理

mockedRandom.tearDown();

おまけ

呼び出し回数を引数から取得することができる

        @Mock
        public int nextInt(Invocation inv, int argMax) {
            System.out.println("呼び出し回数="+inv.getInvocationCount());
            assertEquals("引数チェック",expectedArg,argMax);
            return argMax;
        }

Mock化されたメソッドの引数の前にInvocationを引数として追加する。
Invocation#getInvocationCount()で呼び出し回数を取得可能

6
3
1

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