Mockito:模拟异步方法

时间:2013-08-06 07:33:42

标签: java asynchronous mockito

我需要使用JUnit和Mockito

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

如何模拟myObject来调用upload(arguments,callbackContext)而不是后台线程?

2 个答案:

答案 0 :(得分:2)

你需要在这里做一些事情。首先,使用模拟替换ThreadPool,这样您就可以访问模拟execute了。然后使用ArgumentCaptor中的a verify call访问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());
}

答案 1 :(得分:0)

我认为以下内容可行:

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

但我不太确定。