Using Mockito to mock classes with generic parameters

后端 未结 7 1905
不知归路
不知归路 2020-11-30 19:37

Is there a clean method of mocking a class with generic parameters? Say I have to mock a class Foo which I need to pass into a method that expects a <

7条回答
  •  南笙
    南笙 (楼主)
    2020-11-30 19:45

    Here is an interesting case: method receieves generic collection and returns generic collection of same base type. For example:

    Collection map(Collection assertions);
    

    This method can be mocked with combination of Mockito anyCollectionOf matcher and the Answer.

    when(mockedObject.map(anyCollectionOf(Assertion.class))).thenAnswer(
         new Answer>() {
             @Override
             public Collection answer(InvocationOnMock invocation) throws Throwable {
                 return new ArrayList();
             }
         });
    

提交回复
热议问题