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());
}