如何对`runOnUiThread`中包含的代码进行单元测试?

时间:2016-08-08 07:47:44

标签: android unit-testing kotlin android-runonuithread

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

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

我想要UnitTest myFunction以确保myObject有来电myObjectFunction。但鉴于它是runOnUiThread的包裹,我无法达到它。

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

1 个答案:

答案 0 :(得分:2)

管理以找到使用ArgumentCaptor执行测试的方法。捕获Runnable函数中的runOnUiThread(),然后触发runOnUiArgCaptor.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()

}