JUnit is one of the most popular frameworks for performing Java UT. Mocking is also an aspect that goes hand in hand with JUnit. Unit testing is, of course, performed by developers to test the code they've written.

Let’s consider:

Developer 1 has developed business logic code.

Developer 2 has developed persistence logic code (code that interacts with the database).

If Developer 1 has to use the persistence logic code (method call) written by Developer 2, then Dev 1 might mock that method call. Doing so will let the developer focus only on that code to test it. It’s more like staying in an environment and just testing the code in that environment itself.

While unit testing, developers just test the code in the same environment and mocks the interaction with any other environment.

A more real-time example would be where the code has to interact with the payment gateway. For UT, a developer might not want to send requests to the payment gateway.

There are many frameworks for mocking; Mockito and EasyMock are two of the most popular frameworks. I will be using EasyMock in the example below. Mocking is the process of using a fake object during the UT phase. These frameworks do this by generating proxy objects (java.lang.reflect.Proxy). However, for these purposes, you don't need to know the details about proxy objects.

I will just be using a simple editor for the example, as it will allow for better understanding of the implementations that an IDE might not be able to show.

Now, StudentTest.java is the Test class where the actual action happens. This class has JUnit and the EasyMock API.

The EasyMock framework creates a proxy object/fake object of the class that we want to mock, and this proxy object can be used to return whatever you want as a return value of any of the methods of this class.