Mockito:如何验证传递给我的方法的数组是否包含正确的对象?

Mockito: How do I verify that the array passed to my method contains the right object?

我正在使用 Mockito 1.9.5。我想验证我的方法(将数组作为参数)被调用,其中数组恰好包含一个特定对象。我不知道该怎么做。我有

Mockito.doReturn(new SaveResult[]{}).when(mockConnection).update(org.mockito.Matchers.any(SObject[].class));
…     

Mockito.verify(mockConnection, Mockito.times(1)).update( new Account[]{ acct });

毫不奇怪,第二行失败了,因为尽管参数“acct”与传递的内容相同,但封闭数组却不同。检查此问题的最佳方法是什么?

Mockito 有一个内置匹配器,AdditionalMatchaer#aryEq(T[]) 正好适用于此用例:

Mockito.verify(mockConnection, Mockito.times(1))
       .update(aryEq(new Account[]{ acct }));

除了 Mockito 的内置 aryEq() 匹配器之外,您还可以将 argThat() 与 Hamcrest 的数组匹配器之一一起使用。 arrayContaining 匹配器是一个很好的起点。

请注意,在现代版本的 Mockito(2016 年 9 月的 2.1.0 之后)中,您需要使用 MockitoHamcrest.argThat; ArgumentMatchers.argThat(通过静态继承公开为 Mockito.argThat)不再依赖于汉克雷斯特。这避免了 Hamcrest 和 Mockito 的核心文件之间的版本依赖性。

尽管 MockitoHamcrest 在 2019 年被考虑用于 separation/deprecation/deletion(参见 mockito#1817 and mockito#1819) the file still exists without visible deprecation as of v4.3.1 in January 2022. ArgumentMatchers.argThat is still preferable for lambdas and small custom implementations, but to use Hamcrest's extensive built-in matcher library,您将需要 MockitoHamcrest 作为适配器(或者您需要通过 ArgumentMatchers.argThat 自行调整)。