我有一个调用runOnUiThread的函数,如下所示
fun myFunction(myObject: MyClass, view: MyView) {
// Do something
view.getActivity().runOnUiThread {
myObject.myObjectFunction()
}
}
我想使用UnitTest myFunction来确保myObject调用myObjectFunction.但鉴于它是在runOnUiThread中包装,我无法达到它.
我如何进行单元测试以确保调用runOnUiThread中的代码?
最佳答案 管理以找到使用ArgumentCaptor执行测试的方法.在runOnUiThread()函数中捕获Runnable,然后通过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()
}