I have a function that calls runOnUiThread as below
fun myFunction(myObject: MyClass, view: MyView) {
// Do something
view.getActivity().runOnUiThread {
myObject.myObjectFunction()
}
}
I want to UnitTest myFunction to ensure the myObject has call myObjectFunction. But given that it is wrap in runOnUiThread, I can't get to it.
How could I unit test to ensure codes within runOnUiThread is called?
Manage to find a way to perform the test using ArgumentCaptor. Capture the Runnable in the runOnUiThread() function, and then trigger the run through 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()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With