简体   繁体   English

mockito与第三方课程

[英]mockito when with third party class

I need to use a third party class in Mockito.when as parameter. 我需要在Mockito.when使用第三方类作为参数。 The class does not have equals implementation and hence Mockito.when always returns null except the case where any() is used. 该类没有equals实现,因此Mockito.when总是返回null除了使用any()的情况。

The below always returns null: 以下始终返回null:

when(obj.process(new ThirdParytClass())).thenReturn(someObj);

however, this works 然而,这是有效的

when(obj.process(any(ThirdParytClass.class))).thenReturn(someObj);

But, the problem is the process() method is called twice in the actual code and the use of any() is ambiguous and does not help in covering the multiple scenarios to test. 但是,问题是在实际代码中调用了process()方法两次,并且any()的使用是模糊的,并且无助于覆盖要测试的多个场景。

Extending the class does not help and also leads to other complications. 扩展课程没有帮助,也导致其他并发症。

Is there a way to address the issue. 有没有办法解决这个问题。

If a class doesn't implement a (sensible) equals(Object) , you can always match instances yourself by implementing your own ArgumentMatcher . 如果一个类没有实现(明智的) equals(Object) ,你总是可以通过实现自己的ArgumentMatcher自己匹配实例。 Java 8's functional interfaces make this pretty easy to write (not that it was such a big hardship in earlier versions, but still): Java 8的功能界面使得编写起来相当容易(并不是说它在早期版本中是如此大,但仍然如此):

when(obj.process(argThat(tpc -> someLogic()))).thenReturn(someObj);

More often than not, however, if you just want to compare the class' data members, the built-in refEq matcher would do the trick: 但是,通常情况下,如果您只想比较类的数据成员,内置的refEq匹配器就可以解决这个问题:

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

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

Mockito provides the captor feature that may help you to bypass limitations of equals() method because overriding equals() to make a test pass may be desirable but it is not always the case. Mockito提供了captor功能,可以帮助您绕过equals()方法的限制,因为重写equals()以使测试通过可能是可取的,但情况并非总是如此。
And besides, sometimes, equals() may not be overridable. 此外,有时, equals()可能不会被覆盖。 It is your use case. 这是你的用例。

Here is a example code with an ArgumentCaptor : 以下是带有ArgumentCaptor的示例代码:

@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());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM