Skip to content

Commit

Permalink
feat(junit5): Add a Launcher interceptor (#10)
Browse files Browse the repository at this point in the history
  • Loading branch information
warnyul authored Mar 14, 2024
1 parent 2192659 commit 818dbe5
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 1 deletion.
2 changes: 1 addition & 1 deletion robolectric-extension/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ kotlin {

test {
useJUnitPlatform()
ignoreFailures = true
jvmArgs '-Djunit.platform.launcher.interceptors.enabled=true'
}

dependencies {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package tech.apter.junit.jupiter.robolectric.internal

import java.util.concurrent.atomic.AtomicBoolean
import org.junit.platform.launcher.LauncherInterceptor
import tech.apter.junit.jupiter.robolectric.internal.placeholder.RobolectricPlaceholderTest

class RobolectricLauncherInterceptor : LauncherInterceptor {
private inline val logger get() = createLogger()
private val testRunnerHelper by lazy { JUnit5RobolectricTestRunnerHelper() }

override fun <T : Any?> intercept(invocation: LauncherInterceptor.Invocation<T>): T {
logger.trace { "intercept" }

if (!robolectricLoaded.getAndSet(true)) {
// Create a dummy environment before JUnit5 Jupiter Engine creates any test instance.
// The test class should be loaded by the org.robolectric.internal.AndroidSandbox.SdkSandboxClassLoader.
// Otherwise, the InstrumentationRegistry.getInstrumentation() would be null.
// This environment should be replaced before starting any test.
testRunnerHelper.createTestEnvironmentForClass(RobolectricPlaceholderTest::class.java)
testRunnerHelper.loadRobolectricClassLoader()
testRunnerHelper.clearCachedRobolectricTestRunnerEnvironment()
}

return invocation.proceed()
}

override fun close() {
logger.trace { "close" }
testRunnerHelper.resetClassLoaderToOriginal()
AndroidMainThreadExecutor.shutdown()
}

companion object {
@JvmStatic
private val robolectricLoaded = AtomicBoolean(false)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package tech.apter.junit.jupiter.robolectric.internal.placeholder

import org.junit.jupiter.api.Test

internal class RobolectricPlaceholderTest {
@Test
fun placeholderTestMethod() = Unit
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
tech.apter.junit.jupiter.robolectric.internal.RobolectricLauncherInterceptor

0 comments on commit 818dbe5

Please sign in to comment.