java - 如何在 Android 单元测试中调用测试监听器接口(interface)

标签 java android unit-testing junit

我的 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();
    }
  }
}

我想确保当我传递 param 的某些值时,会调用正确的接口(interface)方法。我可以在标准 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");
}

我也是 Java 的初学者,所以如果这不是用于测试目的的好模式,我愿意将其更改为更易于测试的模式。

最佳答案

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

因此,为了测试 doStuff(param),您不需要真正实现 IEventListener:您需要的只是一个模拟实现IEventListener 并且您必须在测试 doStuff 时验证对 IEventListener 的方法调用的确切数量。这可以通过 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();
    }

}

关于java - 如何在 Android 单元测试中调用测试监听器接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18913827/

相关文章:

java - Spring HATEOAS 嵌入式资源支持

ios - 如何在主应用程序目标中使用单元测试用例(作为 test_spec 添加到开发 pod)?

java - "Content type not set"单元测试 Spring RESTful Controller 时

java - 将 CameraBridgeViewBase 作为服务运行以使用 OpenCV 在后台进行运动检测

使用权重的按钮宽度的Android相对布局

python - 如何从 Python 中的另一个导入函数调用 globals() ?

java - 使用vertx HttpClient连接到https url时vertx ssl握手失败

java - 将 draftCompile 传递给 IntelliJ IDEA 的 GWT 编译器

java - JSOUP - 如何获取登录用户的 Facebook 事件页面的内容?

javascript - 使用数据数组 react native ListView