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