Mockito 101 – Unit Testing in Java Apps

Mockito is an open source framework that allows you to easily create mocks (test doubles).

Mocks are objects that have return values to method executions made during the test and has recorded expectations of these executions.

Mocks can also throw an exception if they receive a call they don’t expect. They are checked during verification to ensure they got all the calls they were expecting.

You can mock both interfaces and classes in the test class

Mockito Annotations

@Mock is used for mock creation. It makes the test class more readable.

@Spy is used to create a spy instance. We can use it instead spy(Object) method.

@InjectMocks is used to instantiate the tested object automatically and inject all the @Mock or @Spy annotated field dependencies into it (if applicable).

To process all above annotations, MockitoAnnotations.initMocks(testClass); is used.

Alternatively, we can also explicitly invoke initMocks() method in @Before annotated Junit method.

public class ServiceTest {


public class ServiceTest {
    public void init() {

Junit Mockito Example

Let us mock the Database and a service call and try to Inject mock DB into service.

public class AppDao {
	public void saveEmployeeData(String empName) {
        System.out.println("Following Data is Successfully saved in DB:  " +empName);

public class AppServiceImpl {	
	ApptDao daoObj;	
	public boolean saveEmployeeData(String empName){
        System.out.println(Following Data is Successfully saved in DB:  " +empName);        
        return true;

Now our service class and Dao class is defined, let us create our test class!

//Annotate the test with the @RunWith(MockitoJUnitRunner.class) so that mockito can process the //annotations.
public class AppServiceImplTest {

	//Annotate service with the @InjectMocks to instantiate and then inject mocked 
	AppServiceImpl service;

        //Annotate the dao fields with the @Mock annotation to have a mock object instantiated
	AppDao daoMock;
	public void saveEmployeeDataTest() {		
		boolean saved = service.saveEmployeeData("John Wick");
		assertEquals(true, saved);
		verify(daoMock, times(1)).saveEmployeeData("John Wick");

Asserts: If the assert condition is true then the program control will execute the next test step but if the condition is false, the execution will stop and further test step will not be executed.


Verify: There won’t be any halt in the test execution even though the verify condition is true or false.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s