Using Mockito for Testing

Mockito is an open source testing framework for Java released under the MIT License.
For More info :

Here I will explain how to use mockito to test the service. But before that we need to know little basics: (Using a simple mock)

import org.junit.jupiter.api.Test;
import org.mockito.Mockito;

import static org.junit.jupiter.api.Assertions.assertEquals;

public class test {
    JSONObject jsonObject = Mockito.mock(JSONObject.class);

    public void fun() {
        assertEquals(false, jsonObject.isEmpty());
        Mockito.when(jsonObject.getString("get")).thenReturn("100"); //when jsonobject.getString("get) is called return "100"
        assertEquals("100", jsonObject.getString("get"));
        Mockito.verify(jsonObject, Mockito.never()).setValue("2", 2);  //set value is never called

Often, we may run into NullPointerException when we try to actually use the instance annotated with @Mock
Most of the time, this happens simply because we forgot to properly enable Mockito annotations.

To enable the Mockito annonation we can make use of the below program which is usually given in @Before class.

	public void init() {

Now I am going to explain how to test kafka and elasticsearch using Mockito. Suppose We have function which reads a record from the kafka and and then puts in the elastic search.

 /*   this is the test class*/
	Records records;
    Record record;

    public void testRecords() {

/* In the manin class we might have the following code not necesaary in  order*/
	if (records.count() <= 0) {
    List<Request> requests = new ArrayList<>();
	for (records<String, String> record : records) {
       String msg = record.value()
         System.out.println("Topic:" + record.key() + "value:" + msg );
    Map<String, Object> inputEvent = (Map<String, Object>) ESMapper.jsonToMap(new JsonParser().parse(msg).getAsJsonObject());

There are several other methods which can be used like:

verify(dao,never()).bulkrequest(any(List.clas));  //that method is never called

Other method for Mocking is given here: