2016-04-25 11 views
2

MockitoのMatcher ...パラメータこのメソッドのシグネチャの2番目のパラメータのための適切Mockitoマッチャ何

List<Something> findSomething(Object o, Integer... ids); 

は、私は、次のマッチャーを試してみました:

when(findSomething(any(), anyInt())).thenReturn(listOfSomething); 
when(findSomething(any(), any())).thenReturn(listOfSomething); 

が、Mockitoが作成されていません私の代理人、返されたListは空です。

答えて

4

このような使用anyVararg()

Application application = mock(Application.class); 
List<Application> aps = Collections.singletonList(new Application()); 

when(application.findSomething(any(), anyVararg())).thenReturn(aps); 

System.out.println(application.findSomething("foo").size()); 
System.out.println(application.findSomething("bar", 17).size()); 
System.out.println(application.findSomething(new Object(), 17, 18, 19, 20).size()); 

が出力:

1 
1 
1 
1

Integer...は、Integerの配列を定義する上の構文糖です。だから、それを模擬するための正しい方法は次のようになります。

when(findSomething(any(), any(Integer[].class))).thenReturn(listOfSomething); 
+0

これは、コンパイラのエラーを引き起こしている: 方法をSomethingService型のfindSomething(Object、Integer ...)は引数には適用されません(Object、Matcher ) – w33z33

関連する問題