by BehindJava

What is the difference between Junit and Mockito

Home » java » What is the difference between Junit and Mockito

In this blog, we are going to know the what is Junit and Mockito and their differences.

Junit vs Mockito

JUnit is a framework that makes it easier to create and execute your unit tests. Mockito (or any other mocking tool) enables you to forego creating “real” objects of production classes in favour of having the framework construct a stub on behalf of you.

Mockito (or any other mocking tool) is a framework that you specifically use to effectively write a particular type of test. Any mocking framework, at its core, enables you to forego creating “real” objects of production classes in favour of having the framework construct a stub on your behalf. By doing this, you have complete control over the fictitious object and can, for instance, confirm the interactions that are occurring.

Having said that, one essential component of unit testing is the desire to isolate your “class under test” from the outside world. To accomplish that, you frequently need to create “test doubles” that you give to an object of your “class under test.” You could manually create all of those “test doubles,” or you could use a mocking framework that produces objects of a specific class for you using reflection techniques. Strangely enough, some people advocate against ever using mocking frameworks, but to be completely honest, I can’t imagine doing that.

In other words, JUnit can be used without a mocking framework. The opposite is also true, but in reality there aren’t many good reasons to use Mockito for anything other than unit testing.

Simple explication with an example

To test APIs in source code, one uses JUnit. Data classes may occasionally be needed for JUnit API testing. We can make those using mockito.

Making replica or dummy items is referred to as mocking.

Several data classes may be used throughout the project. Think of a student object as an illustration. It may include ten criteria, including ID, age, markings, gender, and so forth. However, there is just one API that can return a list of pupils who are older than 10. Therefore, in order to test this API, student objects must be created with all 10 parameters accurate. It is challenging. Therefore, we can only simulate objects with the necessary parameters. We’ll use a dummy student object in our scenario and use age as the lone parameter.

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

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

Therefore, more than two objects can be added to a list and sent to the API to see if it returns students who are older than 10.