7

我有一个调用runOnUiThread如下的函数

fun myFunction(myObject: MyClass, view: MyView) {
    // Do something
    view.getActivity().runOnUiThread {
        myObject.myObjectFunction()
    }
}

我想 UnitTestmyFunction以确保myObjecthas call myObjectFunction。但鉴于它是 wrap in runOnUiThread,我无法理解它。

我如何进行单元测试以确保runOnUiThread调用其中的代码?

4

1 回答 1

8

设法找到一种方法来使用ArgumentCaptor. Runnable在函数中捕获runOnUiThread(),然后触发run throughrunOnUiArgCaptor.value.run()

import com.nhaarman.mockito_kotlin.argumentCaptor
import com.nhaarman.mockito_kotlin.verify
import com.nhaarman.mockito_kotlin.whenever
import org.junit.Before
import org.junit.Test
import org.mockito.Mock

@Mock lateinit var activity: Activity
@Mock lateinit var view: MyView
@Mock lateinit var myObject: MyObject

@Before
fun setUp() {
    MockitoAnnotations.initMocks(this)
}

@Test
fun my_test_function() {
    whenever(view.getActivity()).thenReturn(activity)

    val runOnUiArgCaptor = argumentCaptor<Runnable>()
    val myTestObject = TestObject()

    myTestObject.myFunction(myObject, view)
    verify(activity).runOnUiThread(runOnUiArgCaptor.capture())
    runOnUiArgCaptor.value.run()

    verify(myObject).myObjectFunction()

}
于 2016-08-08T13:37:21.783 回答