Usage of Mockito

Chinmay Venkata Sabbam
art of coding
Published in
4 min readSep 2, 2019

why Mockito and usage of Mockito

Generally Mockito is a framework which is used to avoid the DataBase calls during the runtime while we run the test cases. It uses the Java Reflection concepts to take dummy values as inputs and provided the dummy values as outputs during runtime while we run the test cases.

Mockito is used to test the functionalities of the classes without depend up on the database connection or properties file read or file server read to test a functionality.

Mock objects do the mocking of the real service. A mock object returns a dummy data corresponding to some dummy input passed to it.

Let us consider the below example for better understanding where we use the Mockito

if you write the test Method for B Method in class A using Mockito framework and if you Mock the update call by providing the dummy input values for variables a and b and you will also need to provide a dummy boolean value as a return Type

if you run the test method B written using testNG or Junit -> update Method receives dummy values of a and b and returns dummy value of boolean during runtime, so update method is completely independent on the DB calls.

if you will Mock the Methods which are there inside the Methods of a class while writing the unit test cases using Mockito framework. The Methods of the class does not depend upon the other methods during the runtime, while we executing the unit test cases using testNG or junit.

Steps to write the Mockito Framework

Stepno:1 Add these dependencies in a pom file

stepno:2 Create a test file for the class
If you need to test the HelloMockitoService.java file create HelloMockitoServiceTest.java for better understanding
stepno:3 Initiate the Mockito Frame work
Main Logic Class

TestClass using Mockito Framework

Terminology of Mockito Frame Work

@PowerMockIgnore(“javax.management.*”) : This is used to avoid the Linkage Errors
@PrepareForTest :
In this Block,we need to mentioned the static classess which are used for static Mocks
@Mock : This is used to Mock the objects
@Spy : This is used to spy the Objects , spy is used in different cases, we will discuss these use cases below.
@BeforeClass : This method is executed before the execution of testcases written in the class . objects initiated in this method are alive until the execution of all the testcases written in the class
MockitoAnnotations.initMocks(this) : it can initialize the all Mocks
@BeforeMethod:
This method is executed before the execution of every test case
@InjectMocks: we inject the mocks to call the Real Methods from the Test Methods

There is a anthor concept PowerMockito is like Mockito which is used to Mock some of the objects in some cases

Use Cases of Mockito and Power Mockito

1.Mock instant Methods of other classess : Mockito : invoke with inject object
2. Mock static Methods of other classess : PowerMockito : invoke with inject object
3. Mock private normal Methods : spy with power Mockito : invoke with spy object
4. Mock private static Methods : spy with power Mockito : invoke with spy object
5. Mock private static class variables : spy with whiteBox using power Mockito
6. Mock own public class Methods : spy with PowerMockito
7. Invoking the private Methods : spy with whiteBox using power Mockito : method invoke
8. Invoking the private static Methods : spy with whiteBox using power Mockito : method invoke
9. Suppress the constructors of other classess
10. suppress the static Blocks
11. Declare enums

  1. Mock instant Methods of other classess : Mockito : invoke with inject object
@Mock
HelloMockitoDao
helloMockitoDaoMock;
@InjectMocks
HelloMockitoServiceImpl HelloMockitoServiceMockInjection;
===================== void Methods Mocking ======================Mockito.doNothing().when(helloMockitoDaoMock).someOtherMethodInDao(any(other.class));
HelloMockitoServiceMockInjection.testingMethodInServiceLayer("hello");
===================== instance Method Mocking ===================
Mockito.doReturn(something).when(helloMockitoDaoMock).someOtherMethodInDao(any(other.class));
HelloMockitoServiceMockInjection.testingMethodInServiceLayer("hello");
===================== Throws Exception ==========================
Mockito.doThrow(new Exception()).when(helloMockitoDaoMock).someOtherMethodInDao(any(other.class));
HelloMockitoServiceMockInjection.testingMethodInServiceLayer("hello");

2. Mock static Methods of other classess : PowerMockito : invoke with inject object

@PrepareForTest({ 
Cache.class // class which consists a static Method
})
@InjectMocks
HelloMockitoServiceImpl HelloMockitoServiceMockInjection;
===================== void Methods Mocking ======================
PowerMockito.mockStatic(Cache.class);
PowerMockito.doNothing().when(Cache.class, "put", anyString(),any(Other.class));HelloMockitoServiceMockInjection.testingMethodInServiceLayer("hello");===================== instance Method Mocking ===================
PowerMockito.mockStatic(Cache.class);
PowerMockito.when(Cache.getSomeStaticMethod(anyLong(),any(Other.class), anyLong(),anyLong())).thenReturn(someThing);HelloMockitoServiceMockInjection.testingMethodInServiceLayer("hello");===================== Throws Exception ==========================PowerMockito.mockStatic(Cache.class);PowerMockito.when(Cache.getSomeStaticMethod(anyLong(),any(Other.class), anyLong(),anyLong())).thenThrow(new Exception());HelloMockitoServiceMockInjection.testingMethodInServiceLayer("hello");

3. Mock private normal Methods : spy with power Mockito : invoke with spy object

@PrepareForTest({ 
HelloMockitoServiceImpl.class // class which consists a static Method
})
@InjectMocks

HelloMockitoServiceImpl HelloMockitoServiceMockInjection;
===================== void Methods Mocking ======================
HelloMockitoServiceImpl HelloMockitoServiceImplSpy = PowerMockito.spy(HelloMockitoServiceMockInjection);
PowerMockito.doNothing().when(HelloMockitoServiceImplSpy, "privateMethodName",Mockito.anyList(),Mockito.anyBoolean()); (or)PowerMockito.doNothing().when(HelloMockitoServiceImplSpy, PowerMockito.method(HelloMockitoServiceImpl.class, "privateMethodName")).withArguments(Mockito.any(Other.class),Mockito.any(Boolean.class));HelloMockitoServiceImplSpy.testingMethodInServiceLayer("hello");===================== instance Method Mocking ===================
HelloMockitoServiceImpl HelloMockitoServiceImplSpy = PowerMockito.spy(HelloMockitoServiceMockInjection);
PowerMockito.doReturn(someThing).when(HelloMockitoServiceImplSpy, "privateMethodName",Mockito.anyList(),Mockito.anyBoolean()); (or)PowerMockito.doReturn(someThing).when(HelloMockitoServiceImplSpy, PowerMockito.method(HelloMockitoServiceImpl.class, "privateMethodName")).withArguments(Mockito.any(Other.class),Mockito.any(Boolean.class));HelloMockitoServiceImplSpy.testingMethodInServiceLayer("hello");===================== Throws Exception ==========================HelloMockitoServiceImpl HelloMockitoServiceImplSpy = PowerMockito.spy(HelloMockitoServiceMockInjection);PowerMockito.doThrow(new Exception()).when(HelloMockitoServiceImplSpy, "privateMethodName",Mockito.anyList(),Mockito.anyBoolean()); (or)PowerMockito.doThrow(new Exception()).when(HelloMockitoServiceImplSpy, PowerMockito.method(HelloMockitoServiceImpl.class, "privateMethodName")).withArguments(Mockito.any(Other.class),Mockito.any(Boolean.class));HelloMockitoServiceImplSpy.testingMethodInServiceLayer("hello");

4. Mock private static Methods : spy with power Mockito : invoke with spy object

@PrepareForTest({ 
Cache.class // class which consists a static Method
})
===================== void Methods Mocking ======================PowerMockito.spy(Cache.class);PowerMockito.doNothing().when(Cache.class, "privateMethodName",any(other.class),any(MetricType.class),anyString());Cache.someOtherMethod("hello");===================== instance Method Mocking ===================
PowerMockito.spy(Cache.class);
PowerMockito.doReturn(someThing).when(Cache.class, "privateMethodName",any(other.class),any(other.class),anyString());Cache.someOtherMethod("hello");===================== Throws Exception ==========================
PowerMockito.spy(Cache.class);
PowerMockito.doThrow(new Exception()).when(Cache.class, "privateMethodName",any(other.class),any(other.class),anyString());Cache.someOtherMethod("hello");

5. Mock private static class variables : spy with whiteBox using power Mockito

public static int MAX_ALLOWED_EXECUTION = 6000;
=================================================================
@PrepareForTest({
HelloMockitoServiceImpl.class // class which consists a static Method
})
@InjectMocks
HelloMockitoServiceImpl HelloMockitoServiceMockInjection;
================================================================
HelloMockitoServiceImpl HelloMockitoServiceImplSpy = PowerMockito.spy(HelloMockitoServiceMockInjection);Whitebox.setInternalState(HelloMockitoServiceImpl.class,"MAX_ALLOWED_EXECUTION", 1000);
HelloMockitoServiceImplSpy.testingMethodInServiceLayer("hello");

6. Mock own public class Methods : spy with PowerMockito

@InjectMocks
HelloMockitoServiceImpl HelloMockitoServiceMockInjection;
===================== void Methods Mocking ======================
HelloMockitoServiceImpl HelloMockitoServiceImplSpy = PowerMockito.spy(HelloMockitoServiceMockInjection);
Mockito.
doNothing().when(HelloMockitoServiceImplSpy).someOtherPublicMethodInSameClass(anyString());
HelloMockitoServiceImplSpy.testingMethodInServiceLayer("hello");
===================== instance Method Mocking ===================
HelloMockitoServiceImpl HelloMockitoServiceImplSpy = PowerMockito.spy(HelloMockitoServiceMockInjection);
Mockito.
doReturn(someThing).when(HelloMockitoServiceImplSpy).someOtherPublicMethodInSameClass(anyString());
HelloMockitoServiceImplSpy.testingMethodInServiceLayer("hello");
===================== Throws Exception ==========================
HelloMockitoServiceImpl HelloMockitoServiceImplSpy = PowerMockito.spy(HelloMockitoServiceMockInjection);
Mockito.doThrow(new Exception()).when(HelloMockitoServiceImplSpy).someOtherPublicMethodInSameClass(anyString());
HelloMockitoServiceImplSpy.testingMethodInServiceLayer("hello");

7. Invoking the private Methods : spy with whiteBox using power Mockito : method invoke


HelloMockitoServiceImpl HelloMockitoServiceImplSpy = PowerMockito.spy(HelloMockitoServiceMockInjection);
Whitebox.invokeMethod(HelloMockitoServiceImplSpy, "privateMethodYouNeedToInvoke", methodVariableValue, methodVariableValue);

8. Invoking the private static Methods : spy with whiteBox using power Mockito : method invoke

@PrepareForTest({ 
Cache.class // class which consists a static Method
})
====================================================
PowerMockito.spy(Cache.class);
Whitebox.invokeMethod(Cache.class, "privateMethodYouNeedToInvoke", methodVariableValue, methodVariableValue);

9. Suppress the constructors of other classess

PowerMockito.suppress(HelloMockitoServiceImpl.class.getConstructors());

10. suppress the static Blocks

@RunWith(PowerMockRunner.class)
@SuppressStaticInitializationFor
("some.package.ClassWithStaticInit")

11. Declare enums

@PrepareForTest({ 
EntityType.class // class which consists a static Method
})
EntityType[] entityType = new EntityType[]{EntityType.A, EntityType.B,EntityType.C};
PowerMockito.mockStatic(
EntityType.class);
PowerMockito.when(EntityType.values()).thenReturn(entityType);

--

--