Search code examples
javajunitmockitoraw-types

How to verify a parameterized method using mockito


I'm using mockito to do unit testing. So far it works great for me, until I saw two warnings. I've checked mockito's document, but have no clue how to get rid off the warnings. Here is the code. Any hints are highly appreciated.

class Foo<E> {
    public void doIt(E entity) {
    }
}

class TestCase1 {
    // Compiler Warning -> Unchecked assignment 'Foo<Bar>' to 'Foo'
    private Foo<Bar> fooMock = mock(Foo.class);
}

class TestCase2 {
    private Foo fooMock = mock(Foo.class);
    @Test
    public testBar() {
        fooMock.doIt(any(Bar.class));
        // Compiler Warning -> Unchecked call to 'doIt(E)' as a member of raw type 'Foo'
        verify(fooMock, times(1)).doIt(any(Bar.class));
    }
}

Update 1

I tried the magic annotation @Mock, the warning is gone.

class TestCase3 {
    @Mock
    private Foo<Bar> fooMock;
    @Before
    public void setUp() {
        initMocks(this);
    }
    @Test
    public testBar() {
        fooMock.doIt(any(Bar.class));
        verify(fooMock, times(1)).doIt(any(Bar.class));
    }
}

Solution

  • You can try using Mockito's annotation in order to avoid the first warning. In the second one, Matchers allow to use Generics so this should works fine

    @RunWith(MockitoJUnitRunner.class)
    public class TestCase1 {
    
        @Mock
        private Foo<Bar> fooMock;
    
        @Test
        public void testBar() {
            fooMock.doIt(Matchers.<Bar>any());
            Mockito.verify(fooMock, Mockito.times(1)).doIt(Matchers.<Bar>any());
        }
    }