Mocking Interface

In this post under Mockito, I will show with example how to create mock of an interface.

For our example we will use below interface

DaoI

package package5;
public interface DaoI {
public int insert(Object object);
}

Below is the test class where we create a mock of “DaoI” interface

Test class

package package5;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@ExtendWith(MockitoExtension.class)
public class DaoITest {
@Mock
private DaoI daoI;
@Test
public void testInsert() {
assertNotNull(daoI);
}
}

In the above code, at line 13, I declare a field named “daoI” of type “DaoI” class. We annotate it with “@Mock” annotation.

So creating a mock of an interface is similar to creating a mock of a class.

Leave a comment