Search code examples
javamockitohamcrest

using ArgumentCaptor<List> and hamcrest.hasSize


I'm using Mockito and Hamcrest for unittesting in Java.

Very often I use Hamcrests hasSize to assert some collection has a certain size. A few minutes ago, I was writing a test where I'm capturing a List of the invocation of (replaced the names):

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

The test:

@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
}

Question: The test runs green with the first assertThat, and there's probably other ways to solve this too (for example, implementing ArgumentMatcher<List>), but because I always use hasSize, I'd like to know how I can fix this compile error:

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

Solution

  • One way to workaround this problem is by defining your captor using mockito annotations, like:

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