@Mock and @Spy Mockito Annotations With Example

By | October 15, 2020

In this post, We will learn about @Mock and @Spy Mockito Annotations With Example?

@ Mock Annotation

  • The most Frequently used annotation in Mockito is @Mock
  • Use @Mock annotation to create and inject mocked instances without having to call Mockito.mock(abc.class) manually.
  • We may use org.mockito.Mockito class mock() method to create a mock object of a given class or interface.

@Spy Annotation

  • Use @Spyannotation to spy on an existing instance
  • We usually use Mockito Spy to partial mock an object. When we spy on an object then the real methods are being called unless it’s stubbed.

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

Database Screen Shot

Building the Test Class using Junit 5 and Mockito 3

Let’s build our test classes and use the Mockito extension for it.

Use of @Mock Annotation

Console Output of Above Test class when you run as JUnit Test:

Employee [employee_id=2, employeeName=KK, [email protected], salary=50000.0, doj=Thu Oct 08 09:32:54 IST 2020, bonus=600]

Use of mock method

Console Output of Above Test class when you run as JUnit Test:

Employee [employee_id=2, employeeName=KK, [email protected], salary=50000.0, doj=Thu Oct 08 09:34:01 IST 2020, bonus=600]

Use of @Spy Annotation

Console Output of Above Test class when you run as JUnit Test:

Employee [employee_id=2, employeeName=John, [email protected], salary=90000.0, doj=2020-08-28, bonus=290]

Use of spy method

Console Output of Above Test class when you run as JUnit Test:

Employee [employee_id=2, employeeName=John, [email protected], salary=90000.0, doj=2020-08-28, bonus=290]

You May Also Like:

What is Mocking?
Why Need for mocking?
What are the Benefits of Mockito?
How to mock interface using Mockito example?
Mockito and JUnit Integration Using Maven 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 @Mock and @Spy Mockito Annotations With 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 *