LoginSignup
9
4

More than 5 years have passed since last update.

JUnitのMockでany使ったらInvalidUseOfMatchersExceptionが出た

Last updated at Posted at 2018-09-07

はじめに

JUnitのMockitoでMatchersのany()を使ったらInvalidUseOfMatchersExceptionが出ました。
その解決法をまとめます。

症状

こんな感じのテストコードを書いてみました。

@Test
public void testDoSomething() {
    Hoge hoge = mock(Hoge.class)
    when(hoge.doSomething(any(), "bar")).thenReturn(true);
}

hoge.doSomething()の第一引数は独自定義したクラスだったので、org.mockito.Matchers.any()を入れてます。
第二引数はString型で、特定の文字列を入れてます。

この状態でテストを実行してみると、こんなExceptionが発生しました。

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
Invalid use of argument matchers!
5 matchers expected, 3 recorded:
-> at hogehoge
-> at hogehoge
-> at hogehoge

This exception may occur if matchers are combined with raw values:
    //incorrect:
    someMethod(anyObject(), "raw String");
When using matchers, all arguments have to be provided by matchers.
For example:
    //correct:
    someMethod(anyObject(), eq("String by matcher"));

For more info see javadoc for Matchers class.

分析

When using matchers, all arguments have to be provided by matchers.

このエラーメッセージを読む限り、どうやらすべての引数をmatchers形式にする必要があるようです。
String型の引数の場合、eq()を使えば良さそうです。

解決法

when(hoge.doSomething(any(), "bar")).thenReturn(true);

上記のコードを以下のように変えてみたらExceptionが発生しなくなりました。

when(hoge.doSomething(any(), eq("bar"))).thenReturn(true);

さいごに

解決法まで詳しく書いてある丁寧なエラーメッセージで助かりました。
Matchers良いですね。

9
4
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
9
4