Abhimanyu
08/08/2025, 5:37 PMjava.lang.IllegalStateException: KoinApplication has not been started
Abhimanyu
08/08/2025, 5:38 PMclass HomeScreenTest {
@get:Rule
val composeTestRule = createAndroidComposeRule<MainActivity>()
@Test
fun homeScreenIsDisplayed() {
composeTestRule.onNodeWithText("Home").assertIsDisplayed()
}
}
Abhimanyu
08/08/2025, 5:39 PMclass MyApplication : Application() {
override fun onCreate() {
super.onCreate()
startKoin {
modules(
MyAppModule().module,
)
}
}
}
Abhimanyu
08/08/2025, 5:40 PMclass MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContent {
HomeScreen()
}
}
}
Abhimanyu
08/08/2025, 5:44 PMstartKoin
directly in the test setup.
It didn't work.
@Before
fun setUp() {
startKoin {
modules(MyAppModule().module)
}
}
Abhimanyu
08/09/2025, 1:12 AMInstrumentationTestRunner
class InstrumentationTestRunner : AndroidJUnitRunner() {
override fun newApplication(
classLoader: ClassLoader?,
className: String?,
context: Context?
): Application {
return super.newApplication(
classLoader,
TestApplication::class.java.name,
context
)
}
}
KoinTestRule
class KoinTestRule(
private val modules: List<Module>,
) : TestRule {
override fun apply(
base: Statement,
description: Description,
): Statement {
return object : Statement() {
override fun evaluate() {
try {
stopKoin()
startKoin {
androidContext(
androidContext = InstrumentationRegistry.getInstrumentation().targetContext,
)
modules(
modules = modules,
)
}
base.evaluate()
} finally {
stopKoin()
}
}
}
}
}
TestApplication
class TestApplication : Application() {
override fun onCreate() {
super.onCreate()
startKoin {
androidLogger(
level = Level.ERROR
)
androidContext(
androidContext = this@TestApplication,
)
modules(
modules = testApplicationModule,
)
}
}
}
TestApplicationModule
val testApplicationModule = module {
// Add instrumented common test dependencies here
}
TestModule
internal val androidTestModule = module {
// Add instrumented test-specific dependencies here
}
HomeScreenTest
@RunWith(AndroidJUnit4::class)
internal class HomeScreenTest {
@get:Rule(order = 0)
val koinTestRule = KoinTestRule(
modules = listOf(
MyAppModule().module,
androidTestModule,
),
)
@get:Rule(order = 1)
val composeTestRule = createAndroidComposeRule<MainActivity>()
@Before
fun setup() {
// Setup will be added if needed
}
@Test
fun homeScreen_isDisplayed() {
composeTestRule.onNodeWithText("Home").assertIsDisplayed()
}
}