0

I'd love to be able to get a @Composable context running in the androidTest target of my common project, in order to test higher-order components that reside in commonMain, such as ContentLocalProviders and layouts. Something like:

@Test fun testSomethingComposable() = runComposeTest {
    @Composable fun <M> buildMutableState(model: M) { /* ... */ }

    assertNotNull { buildMutableState(initialState).value }
}

I began with expect fun runComposeTest(content: @Composable ()->Unit) inside of commonTest, but only the jvmTest version works. The createComposeRule().setContent {} function offered by AndroidX only works within an instrumented test.

Any other way around this? Meanwhile, I've just pushed my tests down to jvmTest so that I can move forward.

The jvmTest version:

import androidx.compose.ui.window.application
actual fun runComposeTest(content: @Composable () -> Unit) = runTest {
    application(false) {content}
}

But the following fails in androidTest:

actual fun runComposeTest(content: @Composable () -> Unit) = runTest {
    val rule = createComposeRule()
    rule.setContent(content)
}

... For somewhat obvious reasons.

Tyler Gannon
  • 872
  • 6
  • 19

1 Answers1

0

Turns out they have a test framework that to my knowledge hasn't been announced and receives no mention in the documentation. I added a gist with the full build.gradle.kts.

But basically, you're looking to add org.jetbrains.compose.ui:ui-test-junit4 to your project. I'm running on alpha software so that's:

kotlin { sourceSets {
  val commonTest {
    dependencies {
      /* ... */
      implementation(kotlin("test-junit"))
      implementation(kotlin("test-common"))
      implementation("org.jetbrains.compose.ui:ui-test-junit4:1.2.0-alpha01-dev620")
    }
  }
  val jvmMain by getting {
    dependencies {
      /**
       * Note this is needed for tests to run.
       **/
      implementation(compose.desktop.currentOs)
    }
  }
  val jvmTest by getting {
    dependencies {
      implementation("junit:junit:4.13.2")
    }
  }
}

These tests currently don't work under JUnit5, or so I read somewhere (sorry no reference). Therefore note the explicit kotlin("test-junit") instead of "test", which will load junit5.

Tyler Gannon
  • 872
  • 6
  • 19