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.puzzlers; 6 7 import static org.junit.Assert.assertEquals; 8 import static org.mockito.Mockito.mock; 9 import static org.mockito.Mockito.verify; 10 import static org.mockitoutil.Conditions.bridgeMethod; 11 12 import org.assertj.core.api.Assertions; 13 import org.junit.Test; 14 import org.mockitoutil.TestBase; 15 16 /** 17 * Bridge method is generated by compiler when erasure in parent class is 18 * different. When is different then it means that in runtime we will have 19 * overloading rather than overridding Therefore the compiler generates bridge 20 * method in Subclass so that erasures are the same, signatures of methods match 21 * and overridding is ON. 22 */ 23 @SuppressWarnings("unchecked") 24 public class BridgeMethodPuzzleTest extends TestBase { 25 26 private class Super<T> { say(T t)27 public String say(T t) { 28 return "Super says: " + t; 29 } 30 } 31 32 private class Sub extends Super<String> { 33 @Override say(String t)34 public String say(String t) { 35 return "Dummy says: " + t; 36 } 37 } 38 39 @Test shouldHaveBridgeMethod()40 public void shouldHaveBridgeMethod() throws Exception { 41 Super s = new Sub(); 42 43 assertEquals("Dummy says: Hello", s.say("Hello")); 44 45 Assertions.assertThat(Sub.class).has(bridgeMethod("say")); 46 Assertions.assertThat(s).has(bridgeMethod("say")); 47 } 48 49 @Test shouldVerifyCorrectlyWhenBridgeMethodCalled()50 public void shouldVerifyCorrectlyWhenBridgeMethodCalled() throws Exception { 51 // Super has following erasure: say(Object) which differs from Dummy.say(String) 52 // mock has to detect it and do the super.say() 53 Sub s = mock(Sub.class); 54 Super<String> s_down = s; 55 s_down.say("Hello"); 56 57 verify(s).say("Hello"); 58 } 59 60 @Test shouldVerifyCorrectlyWhenBridgeMethodVerified()61 public void shouldVerifyCorrectlyWhenBridgeMethodVerified() throws Exception { 62 // Super has following erasure: say(Object) which differs from Dummy.say(String) 63 // mock has to detect it and do the super.say() 64 Sub s = mock(Sub.class); 65 Super<String> s_down = s; 66 s.say("Hello"); 67 68 verify(s_down).say("Hello"); 69 } 70 } 71