问题描述:

This question already has an answer here:

  • Calling callbacks with Mockito

    3 answers

网友答案:

You'll need to do a few things here. First, replace the ThreadPool with a mock, so you have access to mock execute at all. Then use an ArgumentCaptor in a verify call to get access to the Runnable. Finally, trigger the Runnable and test the state afterwards.

@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());
}
网友答案:

I think the following would work:

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

but i am not realy sure.

相关阅读:
Top