【问题标题】:How to test listener interface is called within Android Unit Tests如何在 Android 单元测试中调用监听器接口
【发布时间】:2013-09-25 16:02:06
【问题描述】:

我正在尝试为其编写单元测试的 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 的某些值时,会调用正确的接口方法。我可以在标准 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 的初学者,所以如果这不是用于测试目的的好模式,我愿意将其更改为更可测试的东西。

【问题讨论】:

    标签: java android unit-testing junit


    【解决方案1】:

    在这里您要测试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();
        }
    
    }
    

    【讨论】:

    • 最有用的解决方案,但是如果 doStuff1() 需要某个参数而我不关心它的内容怎么办?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-03
    • 1970-01-01
    • 2016-02-15
    • 1970-01-01
    • 1970-01-01
    • 2014-11-18
    • 2015-10-14
    相关资源
    最近更新 更多