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