0

I'm working with unit testing for the first time and I'm lost with some specific cases.

Despite reading a lot I'm confused about how to test a function like this in Android:

void myFunction() {

    MyThread myThread = new MyThread();
    myThread();
}

class MyThread extends Thread {

    public void run() {
        Looper.prepare();
        // Tasks to do in background
        handler.sendEmptyMessage(101);
    }
}

Handler handler = new Handler() {

    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case 101:
            // Get the results
            // Update UI        
        }
    }
};

I've read about "CountDownLatch" as in this SO answer https://stackoverflow.com/a/5722193/1639825 but I don't know how to use this.

Wonton
  • 1,033
  • 16
  • 33

1 Answers1

0

I assume the myFunction() is a member function of an Activity, then you can use Espresso test framework.

Espresso provides a sophisticated set of synchronization capabilities. This characteristic of the framework, however, applies only to operations that post messages on the MessageQueue, such as a subclass of View that's drawing its contents on the screen.

Here's the test code for your logic:

import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.RootMatchers.withDecorView
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import androidx.test.rule.ActivityTestRule
import org.hamcrest.Matchers.`is`
import org.hamcrest.Matchers.not
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith


@RunWith(AndroidJUnit4::class)
@LargeTest
class HandlerActivityTest {

    @get:Rule
    val activityRule = ActivityTestRule(HandlerActivity::class.java)

    @Test
    fun testRefreshUIByHandler() {
        activityRule.activity.myFunction()
        onView(withText("you UI change")).check(matches(isDisplayed()))
    }
}
HunkD
  • 76
  • 2