Initialize Mock object using @Mock annotation of Mockito

In the previous tutorial Overview about Mock in Unit Test, I introduced you all a way to mock an object using the Mockito class. Mockito also supports us another way to initialize the Mock object using @Mock annotation. How is it in details? Let’s find out in this tutorial!

First, I will create a new Maven project as an example:

Initialize Mock object using @Mock annotation of Mockito

With Mockito and JUnit dependencies as follows:

For JUnit 5, in order to run the Unit Test with Maven, we need to declare maven-surefire-plugin Maven plugin with the junit-platform-surefire-provider dependency as follows:

In this tutorial, I also created an application similar to the previous tutorial, but this time, Calculation class will define a method to calculate the subtraction of two numbers.

The Application class has a method that uses the method of class Calculation to calculate the subtraction of two numbers, if the result is greater than 0 then returns true, otherwise false.

I will now write Unit Test for the Application class using the mock object of the Calculation class with the mock object of the Calculation class created using the @Mock annotation.

With the @Mock annotation, to initialize the mock object for the Calculation class, we first need to declare class Calculation with the @Mock annotation within the ApplicationTest class as follows:

Next, we need to declare MockitoExtension.class with the annotation @ExtendWith of JUnit 5 above the ApplicationTest class:

With this extension, Mockito will scan our ApplicationTest class to retrieve all classes that we declare with the @Mock annotation to perform the mock object creation.

The code to test the check() method of the Application class is as follows:

Now we can run the Unit Test to check the results.


Chia sẽ bài viết này ...Share on Facebook
0Tweet about this on Twitter
Share on LinkedIn

Add Comment