简体   繁体   中英

How to test a Jetpack Compose Composable containing rememberLauncherForActivityResult?

How can I test an Android Jetpack Compose composable that calls rememberLauncherForActivityResult ?

For example:

import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts.CreateDocument
import androidx.compose.runtime.Composable
import androidx.compose.material3.Button
import androidx.compose.material3.Text

@Composable
fun PickFileButton() {
  val launcher = rememberLauncherForActivityResult(CreateDocument("text/plain")) { 
    /* do something with the returned Uri */ 
  }
  Button(onClick={launcher.launch("default_file_name.txt")}) {
    Text("Pick File") 
  }
}

Clicking the button launches another activity that the user uses to pick a file.

A test would look like:

import org.junit.Rule
import org.junit.Test
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick

class TestPickFileButton {
  @get:Rule val composeTestRule = createComposeRule()

  @Test
  fun testPickFileButton() {
    composeTestRule.setContent { PickFileButton() }
    composeTestRule.onNodeWithText("Pick File").performClick()
    // now Android CreateDocument activity has launched 
    // and "composeTestRule" cannot interact with this activity
    
    // rest of test eg to check the file was created
  }
}

I cannot complete the test because the external activity has been launched and I can't interact with this activity with the ComposeContentTestRule object.

The solution involves using CompositionLocalProvider to override the default ActivityResultRegistry . This allows you to send a custom response with ActivityResultRegistry.dispatchResult instead of launching an activity.

I had to read the source code for the CreateDocument contract to understand what kind of Intent was expected to be returned.

A working solution for this particular question is:

import android.app.Activity
import android.content.Intent
import android.net.Uri
import androidx.activity.compose.LocalActivityResultRegistryOwner
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.ActivityResultRegistry
import androidx.activity.result.ActivityResultRegistryOwner
import androidx.activity.result.contract.ActivityResultContract
import androidx.activity.result.contract.ActivityResultContracts.CreateDocument
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import androidx.core.app.ActivityOptionsCompat
import androidx.core.net.toFile
import org.junit.Rule
import org.junit.Test

@Composable
fun PickFileButton() {
  val launcher =
      rememberLauncherForActivityResult(CreateDocument("text/plain")) {
        /* do something with the returned Uri */
      }
  Button(onClick = { launcher.launch("default_file_name.txt") }) { Text("Pick File") }
}

class TestPickFileButton {
  @get:Rule val composeTestRule = createComposeRule()

  @Test
  fun testPickFileButton() {

    val testUri = Uri.parse("uri_string_to_return")

    composeTestRule.setContent {

      // ActivityResultRegistry is responsible for handling the 
      // contracts and launching the activity
      val registryOwner = ActivityResultRegistryOwner {
        object : ActivityResultRegistry() {
          override fun <I : Any?, O : Any?> onLaunch(
              requestCode: Int,
              contract: ActivityResultContract<I, O>,
              input: I,
              options: ActivityOptionsCompat?
          ) {
            // don't launch an activity, just respond with the test Uri
            val intent = Intent().setData(testUri)
            this.dispatchResult(requestCode, Activity.RESULT_OK, intent)
          }
        }
      }

      CompositionLocalProvider(LocalActivityResultRegistryOwner provides registryOwner) {
        // any composable inside this block will now use our mock ActivityResultRegistry
        PickFileButton()
      }
    }


    composeTestRule.onNodeWithText("Pick File").performClick()
    // no activity is launched, PickFileButton will received testUri as a respose.

    // rest of test eg to check the file was created
    assert(testUri.toFile().exists())
  }
}

Sources: Discussion in Kotlin Lang Slack Chat , ActivityResultRegistryTest's in Android repository , CompositionLocalProvider

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM