使用 ArgumentCaptor<List> 和 hamcrest.hasSize

using ArgumentCaptor<List> and hamcrest.hasSize

我在 Java 中使用 Mockito 和 Hamcrest 进行单元测试。

我经常使用 Hamcrests hasSize 来断言某些集合具有一定的大小。几分钟前,我正在编写一个测试,我正在捕获 List 的调用(替换名称):

public void someMethod(A someObject, List<B> list)

测试:

@Test
public void test() {
    // (...)
    ArgumentCaptor<List> captor = ArgumentCaptor.forClass(List.class);
    verify(someMock).someMethod(same(otherObject), captor.capture());
    assertThat(captor.getValue().size(), is(2)); // This works
    assertThat(captor.getValue(), hasSize(2)); // This gives a compile error
    // TODO more asserts on the list
}

问题: 第一个 assertThat 测试运行绿色,可能还有其他方法可以解决这个问题(例如,实施 ArgumentMatcher<List>),但因为我总是使用 hasSize,我想知道如何修复这个编译错误:

The method assertThat(T, Matcher<? super T>) in the type MatcherAssert is not applicable for the arguments (List, Matcher<Collection<? extends Object>>)

我自己找到了一个可能的解决方案:

assertThat((List<B>) captor.getValue(), hasSize(2));

解决此问题的一种方法是使用 mockito annotations 定义捕获器,例如:

@RunWith(MockitoJUnitRunner.class)
public class MyTestClass {

    @Captor
    private ArgumentCaptor<List<B>> captor; //No initialisation here, will be initialized automatically

    @Test
    public testMethod() {
        //Testing...
        verify(someMock).someMethod(same(otherObject), captor.capture());
        assertThat(captor.getValue(), hasSize(2));
    }
}