LoginSignup
1
1

More than 5 years have passed since last update.

Mockitoの使い方メモ(初級)

Posted at

JUnitでMockitoを使ったテストをしたので、使い方をメモメモ。

  • NonStrictExpectations
テストコード(抜粋)
@Mocked
protected TimeServiceImpl timeServiceImpl; // @Mockで、モック化したいクラスを定義

    @Test
    public void doTest() {
        new NonStrictExpectations() {
            {
                // 呼び出しする日付をモック化
                Date now = new Date();
                timeServiceImpl.getCurrentTimeDate();
                result = now; // getCurrentTimeDate()を呼んだ時に返ってきてほしい値を書く
            }
        };
        testService.testMethod();
    }

この中で、mock化したいメソッドを呼び出し、変数resultに期待値を定義する。
テストコードから該当メソッドが呼ばれた時の結果がmockされる。

  • Verifications
テストコード(抜粋)
@Mocked
protected CloseableHttpClient mockHttpClient; // @Mockで、モック化したいクラスを定義

    @Test
    public void doTest() {
        testService.testMethod();
        new Verifications() {
            {
                List<HttpUriRequest> requestList = new ArrayList<>();

                mockHttpClient.execute(withCapture(requestList));
                times = 1; // 呼び出し回数の検証

                HttpUriRequest request = requestList.get(0);
                assertThat(request, instanceOf(HttpPost.class)); // 型の検証

                HttpPost post = (HttpPost) request;
                assertThat(post.getURI().toString(), is(fixture.uri)); // URI検証
            }
        };
    }

検証用。
この例だと、「mockHttpClient.execute」メソッドを呼んだ際の情報をrequestListに保持してくれているので、
その内容が正しいかどうか、Listから取り出して検証をする。
例だとget(0)で、1回目しか見てないけど何度も呼んでる場合は拡張for文等で全部見る。
変数timesは、該当メソッドを呼び出した回数で、代入の形で検証ができる。(回数が違っているとassertエラーでJUnit失敗になる)

1
1
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
1
1