How to mock interface using Mockito example

By | October 15, 2020

In this post, We will learn How to set up Mockito Maven Dependency Workspace in Eclipse?

We can use org.mockito.Mockito class mock() method to create a mock object of a given class or interface. This is really the simplest way to mock an object.

We can mock an object using @Mock annotation also. It’s really useful when we want to use the mocked object in multiple test methods because we want to avoid calling the mock() method multiple times. 

When we use @Mock annotation then make sure that we call to initialize the mocked object. We can do this in the testing framework setup method or test method that is executed before the tests.

We have to add the following maven dependency  in pom.xml to use Maven 3.0 

Let’s try to understand the above concept using a demo project

pom.xml

 

EmployeeDAO.java

 

EmployeeDAOImpl.java

 

EmpoyeeService.java

 

EmployeeServiceImpl.java

 

DBUtil.java

 

Employee.java

 

ClientTest.java

 

DbScript

 

InterfaceMethodMockingUsingmockMethodTest.java

 

InterfaceMethodMockingUsingMockAnnotationTest.java

Now right click on either InterfaceMethodMockingUsingmockMethodTest.java or InterfaceMethodMockingUsingMockAnnotationTest.java class and select Run As then Java Application as shown in the below Image

If the Interface method has mocked successfully then the output of the above program would be:

Employee [employee_id=10, employeeName=KK, [email protected], salary=50000.0, doj=Sun Oct 04 18:34:39 IST 2020, bonus=600]

You May Also Like:

What is Mocking?
Why Need for mocking?
What are the Benefits of Mockito?
Mockito and JUnit Integration Using Maven Example
@Mock and @Spy Mockito Annotations With Example
@InjectMocks Annotation in Mockito with Example
Mockito – Verifying Method Calls
@Captor Annotation in Mockito with Example
Adding behavior to mocked object in Mockito
Mocking Void Methods with Mockito
Mocking Exception Throwing using Mockito
Mockito’s mock Overloaded Methods

That’s all about How to mock interface using Mockito example?
If you have any feedback or suggestion please feel free to drop in below comment box.

Leave a Reply

Your email address will not be published. Required fields are marked *