2013-08-06 65 views
3

我需要用JUnit测试这个方法的Mockito的Mockito:模拟异步方法

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

如何嘲笑myObject的调用上传(参数,callbackContext)不是在后台线程?

+0

如果您要模拟'myObject'来在当前线程中调用'upload',而不是像您所问的那样调用'upload';那么你根本就不会测试这种方法 - 你会嘲笑你已经着手测试的东西。 –

回答

0

我认为有以下将工作:

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

,但我真的不肯定。

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