2017-05-09 80 views
0

我是新來的單元測試和我下面的方法我堅持了測試:如何使用mockito測試handler.postDeleyed?

fun freeze(view: View) { 
     view.isClickable = false 
     handler.postDelayed({ 
      view.isClickable = true 
     }, CLICK_TIMEOUT) 
    } 

這裏就是我已經有了:

@Test 
    fun freeze() { 
     var view = mock<View>() 
     viewUtil.freeze(view) 
     assertFalse(view.isClickable) 
    } 

但現在我需要測試圖可點擊之後CLICK_TIMEOUT

我該如何實施這種測試?

回答

3

如果你能嘲笑Handler例如,你可以這樣做:

Handler mockHandler = mock(Handler.class); 
when(mockHandler.postDelayed(any(Runnable.class), anyLong())).thenAnswer(new Answer() { 

    @Override 
    public Object answer(InvocationOnMock invocation) throws Throwable { 
     invocation.getArgumentAt(0, Runnable.class).run(); 
     return null; 
    } 

});