28
34

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.

jMockitがいいよ Verification編

Last updated at Posted at 2013-10-31

えー、前回に引き続きjMockitのお話で、今回はモックの呼ばれっぷりをチェックするAPIの紹介です。

前回までのあらすじ

前回の例だと

new Expectations(){{
   fuga.getName(); result="ホゲ男";
}}

というのを使っていましたが、親戚でNonStrictExpectationsというクラスがあります。
何が違うのかというと、実はExpectationsはモックの挙動定義だけではなくExpectationsに書かれたモックメソッドが呼ばれることをチェックもしています。

なので、

hoge.doAnything();

を実行した時にdoAnything()の内部でfuga.getName()がコールされないとテストは失敗します。
こんな風にExpectationsで

  • fuga.getNameは”ホゲ男”という文字列値を返す
  • fuga.getNameが必ずcallされることをチェックする

ということができます。

Verifications あらたなる旅立ち

…が、ですよ。callされていることのチェックは別途明示的に書きたいものです。
そんな時にVerificationsが使えます。

HogeTest.java
new NonStrictExpectations(){{
   fuga.getName(); result="ホゲ男";
}};

hoge.doAnything();

new Verifications(){{
   fuga.getName(); times=1;
}};

Verifications そして forEachInvocation 伝説へ

これまでモックメソッドは引数なしでしたが、モックメソッドにどんな値が渡されたかテストしたい時もありますよね。

Hoge.java
public void sumAnything(int x) {
    int y = x + 10;
    Fuga fuga = new Fuga();
    fuga.apply(y);
}
HogeTest.java
@Test
public void testSumAnyThing() {
    new NonStrictExpectations(){{
        fuga.apply(anyInt);
    }};

    hoge.sumAnything(5);

    new Verifications(){{
        fuga.apply(anyInt); times=1;
        forEachInvocation = new Object() {
            public void apply(int i) {
                 assertThat(i ,is(15));
            }
        }
    }}
}

returnValueを返すメソッドなら普通にassert出来るのですが、上記例のsumAnything()のようなvoidだと何をassertして良いやら。
こんな時に中で何やっているかをテストするのに便利ですね。

…ってチュートリアルから記述が消えた??

Verifications もう一つの方法 withCapture

モックメソッドに渡ってきた引数をassertする方法にひとつ方法がありました。
http://jmockit.googlecode.com/svn/trunk/www/tutorial/BehaviorBasedTesting.html#withCapture

こっちのほうが簡単かも。

HogeTest.java
@Test
public void testSumAnyThing() {
    new NonStrictExpectations(){{
        fuga.apply(anyInt);
    }};

    hoge.sumAnything(5);

    new Verifications(){{
        int num;
        fuga.apply(num=withCapture()); times=1;
        assertThat(num ,is(15));
    }}
}

次回は、

  • 部分モッキング
  • テスト対象のクラスのprivateメソッドの部分モッキング

の二本でお送りします。 んっがっんん

28
34
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
28
34

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?