我需要用 JUnit 和 Mockito 测试这个方法
function uploadData() {
myObject.getThreadPool().execute(new Runnable() {
@Override
public void run() {
upload(arguments, callbackContext);
}
});
}
如何在不在后台线程中模拟 myObject 来调用 upload(arguments, callbackContext)?
您需要在这里做一些事情。首先,将 ThreadPool
替换为 mock,这样您就可以访问 mock 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());
}