如何在Android单元测试中调用侦听器接口

Cod*_*gue 10 java junit android unit-testing

我在Android应用程序中有以下(示例)结构,我正在尝试编写单元测试:

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();
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我想确保当我传递某些值时param,调用正确的接口方法.我可以在标准的JUnit框架内执行此操作,还是需要使用外部框架?这是我想要的单元测试样本:

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");
}
Run Code Online (Sandbox Code Playgroud)

我也是Java的初学者,所以如果这不是用于测试目的的好模式,我愿意将它改为更可测试的东西.

Deb*_*kia 17

在这里,您要测试EventMonitor.doStuff(param)并在执行此方法时,您希望确保是否IEventListener调用了正确的方法.

因此,为了测试doStuff(param),您不需要真正实现IEventListener:您需要的只是模拟实现,IEventListener并且您必须IEventListener在测试时验证方法调用的确切数量doStuff.这可以通过Mockito或任何其他模拟框架来实现.

以下是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();
    }

}
Run Code Online (Sandbox Code Playgroud)