Mockito runnable:想要但没有被调用?

Mockito runnable: wanted but not invoked?

在提交错误报告之前,我想确保我没有做错什么。这真的很奇怪。设置:

robolectric3.0;模仿 1.10.19

被测单元:

public BbScrollView( Context context ){
  this( context, null );
}

public BbScrollView( Context context, AttributeSet attrs ) {
  super( context, attrs );

  mScrollTask = new Runnable() {

    public void run() {
      checkForStopped();
    }
  };
}

public void checkForStopped(){
  int newPosition = getScrollY();
  // the rest is irrelevant , but I hit a breakpoint here.
}

public void startScrollTask() {
  mInitialPosition = getScrollY();
  postDelayed( mScrollTask, mTimeUntilNextCheckForStopped );
}

测试:

@RunWith(RobolectricGradleTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 21)
public class BbScrollViewTests {

  @Test
  public void test_startScrollTask(){
    BbScrollView uut = spy( new BbScrollView( RuntimeEnvironment.application ) );

    // This calls the method above that enqueues the runnable
    uut.startScrollTask();

    // Robolectric runs the runnable
    ShadowLooper.runUiThreadTasksIncludingDelayedTasks();

    // I can hit a breakpoint inside this method but verify() fails
    verify( uut ).checkForStopped();
  }
}

测试失败:

Wanted but not invoked:
bbScrollView.checkForStopped();
-> at com.myapp.android.BbKit.test.view.BbScrollViewTests.test_startScrollTask(BbScrollViewTests.java:62)

However, there were other interactions with this mock:
bbScrollView.startScrollTask();
-> at com.myapp.android.BbKit.test.view.BbScrollViewTests.test_startScrollTask(BbScrollViewTests.java:58)

bbScrollView.getScrollY();
-> at com.myapp.android.BbKit.test.view.BbScrollViewTests.test_startScrollTask(BbScrollViewTests.java:58)

bbScrollView.$$robo$getData();
-> at com.myapp.android.BbKit.test.view.BbScrollViewTests.test_startScrollTask(BbScrollViewTests.java:58)

bbScrollView.postDelayed(
    com.myapp.android.BbKit.view.BbScrollView@7f830761,
    100
);
-> at com.myapp.android.BbKit.test.view.BbScrollViewTests.test_startScrollTask(BbScrollViewTests.java:58)

bbScrollView.$$robo$getData();
-> at com.myapp.android.BbKit.test.view.BbScrollViewTests.test_startScrollTask(BbScrollViewTests.java:58)

我再说一遍:我在 verify() 检查的方法中设置了断点 但测试失败了。我还尝试在 checkForStopped() 中创建一个虚拟方法并对其进行验证但无济于事。我还在 robolectric UI 线程调用的任一侧尝试了 1000ms thread.sleep。我的猜测是 robolectric 和 mockito 的反射之间的交互正在发生什么?

根据这个 Mockito 原则,您发现了一些非常有趣的预期但不直观的行为:要创建间谍,Mockito makes a shallow copy of the original object

当您在构造函数中创建匿名内部 Runnable 时,Runnable 包含对 BbScrollView.this 的隐式引用,您的 原始 BbScrollView 对象。然后,您在创建间谍时创建一个副本,并且对原始 BbScrollView 的引用仍然存在。这意味着您对 checkForStopped 的调用发生在 Mockito 无法观察到的原始对象上,而不是间谍。

解决此问题的一种方法是将您的匿名内部 Runnable 创建移动到您的 startScrollTask 方法,在间谍上调用,因此 this 指的是间谍。当 Runnable 为 运行 时,它将调用间谍而不是真实对象上的方法,允许 Mockito 拦截并验证调用。