Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit test code wrapped in `runOnUiThread`?

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?

like image 830
Elye Avatar asked Aug 08 '16 07:08

Elye


1 Answers

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()

}
like image 131
Elye Avatar answered Nov 01 '22 16:11

Elye