Unit Testing Mockito

Unit Testing Mockito

This tutorial assumes that you have some experience working with JUnit to perform unit testing of java classes. Mockito is an open source test framework which allows to create mock objects (Test double) to perform unit test in TDD (Test Driven Development or BDD(Behavior Driven Development).

In object oriented programming performing unit testing is difficult where class are dependent on many classes. For this reason, developer creates mock object that is simulation of actual objects whose behavior is same as real objects. Mockito framework allows you to create mock objects at the runtime using java proxy mechanism. You might have heard of below popular framework:

Out of all above I found Mockito easy to use to perform unit testing. It supports creating of mock object in various ways:

  • static mock method call: Below is sample how we use mock method and detail class you will see in the bottom:

  • Using annotation @mock: If you use annotation then you could initialize mock object either annotate class with @RunWith(MockitoJUnitRunner.class) or using MockitoAnnotations.initMocks(this) as below:

Unit Testing Mockito

To keep you aware: It has certain limitation where test can not be perform:

  • anonymous classes
  • primitive types
  • final classes

To understand better I will create sample maven project name: UnitTestingWithMockito with domain object, interface its implementation, class which call interface and consume its method. To perform unit test create two test classes which use different ways to create mock object. Below is final project structure:

Unit Testing Mockito

  •  Dependencies in pom.xml file:

  • Domain object Message.java:

  •  Create interface IMockitoMessage.java with one sample method:

  • MockitoMessageImpl.java which implements IMockitoMessage:

  • Client which use IMockitoMessage interface and call its method to get data:

  • Test class 1: MockitoMessageImpleClientTest.java where you can use either @RunWith(MockitoJUnitRunner.class) annotation or MockitoAnnotations.initMocks(this) to create mock object to perform unit test:

  •  Test Class 2: MockitoMessageImpleTestUsingMockMethod.java where mock method has been used to create mock object and executed unit test:

  • To run unit test right click any of above two test class –> Run As –> JUnit Test:

Unit Testing Mockito

  • You will see below successful test result:

Unit Testing Mockito

  • For more details please refer Mockito documentation on its official site here 

download  Download project: UnitTestingWithMockito

Leave a Reply

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

I am not Robot *