Created
September 24, 2013 15:31
-
-
Save tzachz/6686530 to your computer and use it in GitHub Desktop.
Confusing Mockito behavior with overriding interfaces
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.kenshoo.rtb.tools; | |
import org.junit.Test; | |
import static junit.framework.Assert.assertTrue; | |
import static org.mockito.Mockito.mock; | |
import static org.mockito.Mockito.when; | |
/** | |
* Created by IntelliJ IDEA. | |
* User: tzachz | |
* Date: 9/24/13 | |
*/ | |
public class OddMockitoStuffTest { | |
private static final Long INPUT = 3l; | |
interface Parent<T> { | |
boolean apply(T input); | |
} | |
interface Child extends Parent<Long> { | |
@Override | |
public boolean apply(Long input); | |
} | |
interface EmptyChild extends Parent<Long> {} | |
@Test | |
public void mockAndRunChildSucceeds() throws Exception { | |
Child mock = mock(Child.class); | |
when(mock.apply(INPUT)).thenReturn(true); | |
boolean result = mock.apply(INPUT); | |
assertTrue(result); | |
} | |
@Test | |
public void mockChildAndRunParentFails() throws Exception { | |
Child mock = mock(Child.class); | |
when(mock.apply(INPUT)).thenReturn(true); | |
// This is what happens explicitly in Collections2.filter - | |
// it executes the parent's apply(Object) and not the child's apply(Long) | |
boolean result = ((Parent<Long>)mock).apply(INPUT); | |
// this fails! | |
assertTrue(result); | |
} | |
@Test | |
public void ifChildEmptyItsOK() throws Exception { | |
EmptyChild mock = mock(EmptyChild.class); | |
when(mock.apply(INPUT)).thenReturn(true); | |
// there's only the parent's method to mock and run, so this passes | |
boolean result = ((Parent<Long>)mock).apply(INPUT); | |
assertTrue(result); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment