koin icon indicating copy to clipboard operation
koin copied to clipboard

Be able to declare dependencies in junit 5 @BeforeAll

Open laurentthiebaudezm opened this issue 10 months ago • 0 comments

Hi! I'd like to be able to declare a component in a compagnon object / @JvmStatic beforeAll statement.

Ex:

class MyTest: KoinTest {

  @JvmField
  @RegisterExtension
  val koinTestExtension = KoinTestExtension.create { modules(module { moduleDeclaration }) }

  val Module.moduleDeclaration: KoinDefinition<myServiceInstance>
        get() = single { myServiceInstance() }

  companion object {
    @JvmStatic
    @BeforeAll
    fun beforeAll() {
      declare { ADependencyService } // error is here
    }
  }
}

Error is:

Cannot infer type for this parameter. Please specify it explicitly.
 Unresolved reference. None of the following candidates is applicable because of a receiver type mismatch: fun <reified T : Any> KoinTest. declare(qualifier: Qualifier? = ..., noinline instance: () -> T): T

To make it compile I must use:

companion object: KoinTest { ...}

However this fails at runtime with:

KoinApplication has not been started
 java.lang.IllegalStateException: KoinApplication has not been started

I guess that the compagnon object is instanciated before the class, which is responsible to start koin. Any idea how to make it work? It is a pîty that beforeAll cannot be used with koin.

Versions: junit-juîter 5.11.4 & koin 4.0.2

laurentthiebaudezm avatar Feb 18 '25 08:02 laurentthiebaudezm