Please help in writing Junit for the interface default method.
public interface ABC {
default List getSrc(DEF def, XYZ xyz) t
If you're using Mockito, the simplest way to unit-test a default (AKA "defender") method is to make a spy1 using the interface class literal2. The default method can then be invoked on the returned spy instance as normal. The following example demonstrates:
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.spy;
interface OddInterface {
// does not need any unit tests because there is no default implementation
boolean doSomethingOdd(int i);
// this should have unit tests because it has a default implementation
default boolean isOdd(int i) {
return i % 2 == 1;
}
}
public class OddInterfaceTest {
OddInterface cut = spy(OddInterface.class);
@Test
public void two_IS_NOT_odd() {
assertFalse(cut.isOdd(2));
}
@Test
public void three_IS_odd() {
assertTrue(cut.isOdd(3));
}
}
(tested with Java 8 and mockito-2.24.5)
1People often warn using a spy
can be indicative of a code or test smell, but testing a default method is a perfect example of when using a spy
is a good idea.
2As of the time of this writing (2019), the signature of spy
which accepts a class literal is marked as @Incubating
, but has been around since mockito-1.10.12 which was released in 2014. Furthermore, support for default methods in Mockito has been around since mockito-2.1.0 which was released in 2016. It seems like a safe bet that this method will continue to work in future versions of Mockito.