1 /* 2 * Copyright (c) 2007 Mockito contributors 3 * This program is made available under the terms of the MIT License. 4 */ 5 6 package org.mockitousage.bugs; 7 8 import org.junit.Test; 9 import org.mockito.Mockito; 10 import org.mockitoutil.TestBase; 11 12 import java.lang.reflect.InvocationHandler; 13 import java.lang.reflect.Method; 14 import java.lang.reflect.Proxy; 15 import java.util.Iterator; 16 import java.util.LinkedList; 17 import java.util.List; 18 19 import static org.junit.Assert.assertEquals; 20 import static org.junit.Assert.assertNotNull; 21 import static org.mockito.Mockito.verify; 22 23 @SuppressWarnings("unchecked") 24 //see issue 200 25 public class InheritedGenericsPolimorphicCallTest extends TestBase { 26 27 protected interface MyIterable<T> extends Iterable<T> { iterator()28 MyIterator<T> iterator(); 29 } 30 31 protected interface MyIterator<T> extends Iterator<T> { 32 // adds nothing here 33 } 34 35 MyIterator<String> myIterator = Mockito.mock(MyIterator.class); 36 MyIterable<String> iterable = Mockito.mock(MyIterable.class); 37 38 @Test shouldStubbingWork()39 public void shouldStubbingWork() { 40 Mockito.when(iterable.iterator()).thenReturn(myIterator); 41 assertNotNull(((Iterable<String>) iterable).iterator()); 42 assertNotNull(iterable.iterator()); 43 } 44 45 @Test shouldVerificationWorks()46 public void shouldVerificationWorks() { 47 iterable.iterator(); 48 49 verify(iterable).iterator(); 50 verify((Iterable<String>) iterable).iterator(); 51 } 52 53 @Test shouldWorkExactlyAsJavaProxyWould()54 public void shouldWorkExactlyAsJavaProxyWould() { 55 //given 56 final List<Method> methods = new LinkedList<Method>(); 57 InvocationHandler handler = new InvocationHandler() { 58 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 59 methods.add(method); 60 return null; 61 }}; 62 63 iterable = (MyIterable<String>) Proxy.newProxyInstance( 64 this.getClass().getClassLoader(), 65 new Class<?>[] { MyIterable.class }, 66 handler); 67 68 //when 69 iterable.iterator(); 70 ((Iterable<String>) iterable).iterator(); 71 72 //then 73 assertEquals(2, methods.size()); 74 assertEquals(methods.get(0), methods.get(1)); 75 } 76 } 77