Skip to content

Commit 52dad80

Browse files
committed
fix issue with @RobolectricTest failing
The first class with @RobolectricTest would run fine, but then every test class after in the run would fail with a looper already started error. This fix was discovered by looking through Robolectric's RobolectricTestRunner and SandboxTestRunner clases. Most of the pre-existing kotest-extensions-robolectric code seemed to be reripped from those 2 classes and I notice this was something this extension was not doing. Looper's are linked to a thread so this seems related, however I don't understand any more than this to explain why this fixes the error.
1 parent 66fd002 commit 52dad80

File tree

1 file changed

+14
-5
lines changed

1 file changed

+14
-5
lines changed

OneSignalSDK/onesignal/core/src/test/java/com/onesignal/extensions/RobolectricExtension.kt

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,13 +7,15 @@
77
package com.onesignal.extensions
88

99
import android.app.Application
10+
import io.kotest.common.runBlocking
1011
import io.kotest.core.extensions.ConstructorExtension
1112
import io.kotest.core.extensions.TestCaseExtension
1213
import io.kotest.core.spec.AutoScan
1314
import io.kotest.core.spec.Spec
1415
import io.kotest.core.test.TestCase
1516
import io.kotest.core.test.TestResult
1617
import org.robolectric.annotation.Config
18+
import java.util.concurrent.Callable
1719
import kotlin.reflect.KClass
1820
import kotlin.reflect.full.findAnnotation
1921
import kotlin.time.Duration
@@ -94,11 +96,18 @@ internal class RobolectricExtension : ConstructorExtension, TestCaseExtension {
9496
testCase: TestCase,
9597
execute: suspend (TestCase) -> TestResult,
9698
): TestResult {
97-
val containedRobolectricRunner = ContainedRobolectricRunner(testCase.spec::class.getConfig())
98-
containedRobolectricRunner.containedBefore()
99-
val result = execute(testCase)
100-
containedRobolectricRunner.containedAfter()
101-
return result
99+
val containedRobolectricRunner =
100+
ContainedRobolectricRunner(testCase.spec::class.getConfig())
101+
// sdkEnvironment.runOnMainThread is important to ensure Robolectric's
102+
// looper state doesn't carry over to the next test class.
103+
return containedRobolectricRunner.sdkEnvironment.runOnMainThread(
104+
Callable {
105+
containedRobolectricRunner.containedBefore()
106+
val result = runBlocking { execute(testCase) }
107+
containedRobolectricRunner.containedAfter()
108+
result
109+
},
110+
)
102111
}
103112
}
104113

0 commit comments

Comments
 (0)