How to test the listener interface is called in the Android Unit test

I have the following (approximate) structure in my Android application that I am trying to write unit test for:

class EventMonitor { private IEventListener mEventListener; public void setEventListener(IEventListener listener) { mEventListener = listener; } public void doStuff(Object param) { // Some logic here mEventListener.doStuff1(); // Some more logic if(param == condition) { mEventListener.doStuff2(); } } } 

I want to make sure that when passing certain param values, the correct interface methods are called. Can I do this as part of the standard JUnit framework, or do I need to use an external framework? This is a unit test sample that I would like:

 public void testEvent1IsFired() { EventMonitor em = new EventMonitor(); em.setEventListener(new IEventListener() { @Override public void doStuff1() { Assert.assertTrue(true); } @Override public void doStuff2() { Assert.assertTrue(false); } }); em.doStuff("fireDoStuff1"); } 

I also start in Java, so if this is not a good test sample, I am ready to change it to something more verifiable.

+6
source share
1 answer

Here you want to test EventMonitor.doStuff(param) , and during the execution of this method you want to make sure that the correct methods were called in IEventListener or not.

So, in order to test doStuff(param) , you do not need to have a real implementation of IEventListener : you only need a mock implementation of IEventListener , and you need to check the exact number of invocation methods on IEventListener when testing doStuff . This can be achieved with the help of Mockito or any other mocking structure.

Here is an example with Mockito:

 import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; public class EventMonitorTest { //This will create a mock of IEventListener @Mock IEventListener eventListener; //This will inject the "eventListener" mock into your "EventMonitor" instance. @InjectMocks EventMonitor eventMonitor = new EventMonitor(); @Before public void initMocks() { //This will initialize the annotated mocks MockitoAnnotations.initMocks(this); } @Test public void test() { eventMonitor.doStuff(param); //Here you can verify whether the methods "doStuff1" and "doStuff2" //were executed while calling "eventMonitor.doStuff". //With "times()" method, you can even verify how many times //a particular method was invoked. verify(eventListener, times(1)).doStuff1(); verify(eventListener, times(0)).doStuff2(); } } 
+15
source

Source: https://habr.com/ru/post/954240/


All Articles