MOCKITO: What is it and how is it different from Junit

JUnit is a framework that helps with writing and running your unit tests.

Mockito (or any other mocking tool) is a framework that you specifically use to efficiently write certain kind of tests. At it's core, any mocking framework allows you omit instantiating "real" objects of production classes, instead the mocking framework creates a stub for you. Doing so gives you full control over that mocked object and enables you to verify the interactions taking place for example.

Having said that: one core aspect in unit testing is the fact that you want to isolate your "class under test" from anything else in the world. In order to do that, you very often have to create "test doubles" that you provide to an object of your "class under test". You could create all those "test doubles" manually; or you use a mocking framework that generates object of a certain class for you using reflection techniques. Interestingly enough, some people advocate to never use mocking frameworks; but honestly: I can't imagine doing that.

In other words: you can definitely use JUnit without using a mocking framework. Same is true for the reverse direction; but in reality, there are not many good reasons why you would want to use Mockito for anything else but unit testing.


Layman's Explaination with Example

JUnit is used to test API's in source code. To test API's in JUnit, sometimes we may require data classes. To create those, we can use mockito.

Mock refers to creating duplicate or dummy objects.

We might be using many data classes in the project. For Example, think of a Student object.It might have some 10 parameters like id,age,marks,gender e.t.c. But you have one API to return a list of students whose age is greater than 10. So, to test this API we need to create student objects with all 10 parameters right. It is difficult. So, we can mock objects only with the required parameters. In our scenario, we will mock student obj with only age as a parameter.

Student student1=mock(Student.class);
when(student1.getAge()).thenReturn(20);

Student student2=mock(Student.class);
when(student2.getAge()).thenReturn(8);

So,above 2 objs can be added to a list and can be passed to API to test if API returns students who has age greater than 10.


JUnit is the Java library used to write tests (offers support for running tests and different extra helpers - like setup and teardown methods, test sets etc.). Mockito is a library that enables writing tests using the mocking approach.

See here a nice article on the mocking vs non mocking tests: http://martinfowler.com/articles/mocksArentStubs.html