我有一个调用runOnUiThread
的函数,如下所示
fun myFunction(myObject: MyClass, view: MyView) {
// Do something
view.getActivity().runOnUiThread {
myObject.myObjectFunction()
}
}
我想要UnitTest myFunction
以确保myObject
有来电myObjectFunction
。但鉴于它是runOnUiThread
的包裹,我无法达到它。
我如何进行单元测试以确保调用runOnUiThread
内的代码?
答案 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()
}