3

我需要用 JUnit 和 Mockito 测试这个方法

 function uploadData() {
    myObject.getThreadPool().execute(new Runnable() {
                @Override
                public void run() {
                    upload(arguments, callbackContext);
                }
            });
        }

如何模拟 myObject 调用不在后台线程中的上传(参数,回调上下文)?

4

2 回答 2

2

你需要在这里做一些事情。首先,将 替换ThreadPool为 mock,这样您就可以完全访问 mock execute。然后使用ArgumentCaptorin调用verify访问Runnable. 最后,触发Runnable并测试之后的状态。

@Test public void shouldUploadInBackground() {
  // declare local variables
  MyObject mockMyObject = Mockito.mock(MyObject.class);
  ThreadPool mockThreadPool = Mockito.mock(ThreadPool.class);
  ArgumentCaptor<Runnable> runnableCaptor =
      ArgumentCaptor.forClass(Runnable.class);

  // create the system under test
  when(mockMyObject.getThreadPool()).thenReturn(mockThreadPool);
  SystemUnderTest yourSystemUnderTest = createSystem(mockThreadPool);

  // run the method under test
  yourSystemUnderTest.uploadData();

  // set the runnableCaptor to hold your callback
  verify(mockThreadPool).execute(runnableCaptor.capture());

  // here you can test state BEFORE the callback executes
  assertFalse(yourSystemUnderTest.isDataUploaded());

  // call run on the callback
  runnableCaptor.getValue().run();

  // here you can test state AFTER the callback executes
  assertTrue(yourSystemUnderTest.isDataUploaded());
}
于 2013-08-06T18:30:05.283 回答
0

我认为以下方法会起作用:

Mockito.doAnswer(new Answer() {
    @Override
    public Object answer(InvocationOnMock invocation) throws Throwable {
        upload(arguments, callbackContext);
    }).when(myObjectSpy.getThreadPool()).execute(Mockito.any(Runnable.class));

但我不太确定。

于 2013-08-06T07:53:07.153 回答