找到你要的答案

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

Q:Mockito:我该如何确认数组传递给我的方法包含正确的对象吗?

I’m using Mockito 1.9.5. I want to verify that my method (which takes an array as a param) was called in which the array contains exactly one specific object. I’m having trouble figuring out how to do this. I have

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

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

Unsurprisingly, the second line fails because although the argument, “acct” is the same as what is passed, the enclosing array is not. What is the best way to check for this?

我用mockito 1.8.5。我想验证我的方法(以数组作为参数)被称为该数组包含一个特定的对象。我很难弄明白怎么做。我有

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

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

毫不奇怪,因为虽然争论第二线失败,“客户”是什么是通过相同的,封闭的阵列是不。检查这个最好的方法是什么?

answer1: 回答1:

Mockito has a builtin matcher, AdditionalMatchaer#aryEq(T[]) for this usecase exactly:

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

mockito具有内部匹配,additionalmatchaer # aryeq(T [ ])这个用例准确:

Mockito.verify(mockConnection, Mockito.times(1))
       .update(aryEq(new Account[]{ acct }));
answer2: 回答2:

In addition to Mockito's built-in aryEq() matcher, you can use argThat() with one of Hamcrest's array Matchers. The arrayContaining matcher is a good starting point.

This is also the best way to specify matchers of arrays where you need to test instance equality or any custom comparison.

除了mockito内置的aryeq()匹配,你可以使用一个argthat() hamcrest的阵列匹配。arraycontaining匹配的出发点是好的。

这也是最好的方法来指定匹配的数组,你需要测试实例的平等或任何自定义的比较。

java  junit  arguments  mockito  verify