Using Mockito for Testing
Mockito is an open source testing framework for Java released under the MIT License.
For More info : https://site.mockito.org/
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 com.ibm.wsc.infohub.json.JSONObject; 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); @Test 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.
@Before public void init() { MockitoAnnotations.initMocks(this); }
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*/ @Mock Records records; @Mock Record record; @Test public void testRecords() { when(records.count()).thenReturn(1); when(records.iterator()).thenReturn(Arrays.asList(records).iterator()); when(records.value()).thenReturn("{randomid:123}"); testclass.checkrecords(records); verify(dao).bulkRequest(any(List.class)); } /* In the manin class we might have the following code not necesaary in order*/ if (records.count() <= 0) { return; } 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()); requests.add(createDocumentinES); bulkRequest(requests);
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:
http://thebadengineer.com/powermockito-for-mocking-and-testing/
One thought on “Using Mockito for Testing”