Java 使用第三方类时的mockito

Java 使用第三方类时的mockito,java,junit,mockito,matcher,Java,Junit,Mockito,Matcher,我需要在Mockito.when中使用第三方类作为参数。该类没有equals实现,因此Mockito.when始终返回null,使用any()的情况除外 以下字段始终返回空值: when(obj.process(new ThirdParytClass())).thenReturn(someObj); 然而,这是可行的 when(obj.process(any(ThirdParytClass.class))).thenReturn(someObj); 但是,问题是process()方法在实际代

我需要在
Mockito.when
中使用第三方类作为参数。该类没有equals实现,因此
Mockito.when
始终返回
null
,使用
any()
的情况除外

以下字段始终返回空值:

when(obj.process(new ThirdParytClass())).thenReturn(someObj);
然而,这是可行的

when(obj.process(any(ThirdParytClass.class))).thenReturn(someObj);
但是,问题是
process()
方法在实际代码中被调用了两次,并且
any()
的使用是不明确的,不能帮助覆盖要测试的多个场景

延长课程时间无济于事,还会导致其他并发症


有没有办法解决这个问题。

如果一个类没有实现(合理的)
equals(对象)
,您可以通过实现自己的实例来匹配实例。Java 8的功能接口使其非常容易编写(虽然在早期版本中这不是一个很大的困难,但仍然如此):

但是,如果您只想比较类的数据成员,则内置匹配器通常会执行以下操作:

ThirdParytClass expected = new ThirdParytClass();
// set the expected properties of expected

when(obj.process(refEq(expected))).thenReturn(someObj);

Mockito提供了captor功能,可以帮助您绕过
equals()
方法的限制,因为覆盖
equals()
以使测试通过可能是可取的,但并非总是如此。
此外,有时,
equals()
可能不可重写。这是您的用例

下面是一个带有
参数捕获器的示例代码:

@Mock
MyMockedClass myMock;

@Captor
ArgumentCaptor argCaptor;

@Test
public void yourTest() {
    ThirdPartyClass myArgToPass = new ThirdPartyClass();
    // call the object under test
     ...
    //
    Mockito.verify(myMock).process(argCaptor.capture());
    // assert the value of the captor argument is the expected onoe
    assertEquals(myArgToPass , argCaptor.getValue());
}
@Mock
MyMockedClass myMock;

@Captor
ArgumentCaptor argCaptor;

@Test
public void yourTest() {
    ThirdPartyClass myArgToPass = new ThirdPartyClass();
    // call the object under test
     ...
    //
    Mockito.verify(myMock).process(argCaptor.capture());
    // assert the value of the captor argument is the expected onoe
    assertEquals(myArgToPass , argCaptor.getValue());
}