Search code examples
javamockitoverify

Mockito Verify on passed sub type only sees super type


I cannot easily verify 2 individual and unique call of a sub type class to a method which takes a supertype

I have a scenario that acts like this...

Both B and C extend abstract type A

With

public class X {
    public String doSomething(A a){
        return "";
    }
}

Test

@Test
public void testExtensionVerify(){
 X x = mock(X.class);
 B b = new B();
 C c = new C();
 x.doSomething(b);
 x.doSomething(c);

 verify(x, times(1)).doSomething(any(B.class));  //fails.  
}

verify times(1) fails... It sees 2 calls instead of 1 probably because B's reference in the method signature is the super type A.

The problem is that I cannot verify each call uniquely

I know that I can swtich to eq(b) and eq(c) instead of any() but I have no handle to them in my real case as they are created in the Object under test. Another option might be to do a ArgumentCaptor and test the instance but its annoying.

Any other solutions?


Solution

  • You can use isA:

    verify(x, times(1)).doSomething(isA(B.class)); 
    

    http://docs.mockito.googlecode.com/hg/1.9.5/org/mockito/Matchers.html

    The any family methods don't do any type checks, those are only here to avoid casting in your code. If you want to perform type checks use the isA(Class) method. This might however change (type checks could be added) in a future major release.

    public class XTest {
      @Test
      public void testExtensionVerify(){
        X x = mock(X.class);
        B b = new B();
        C c = new C();
        x.doSomething(b);
        x.doSomething(c);
    
        verify(x, times(1)).doSomething(isA(B.class));
        verify(x, times(1)).doSomething(isA(C.class));
      }
    }