InsertKoinIO / koin

Koin - a pragmatic lightweight dependency injection framework for Kotlin & Kotlin Multiplatform
https://insert-koin.io
Apache License 2.0
9.08k stars 719 forks source link

How to set different modules for testing (other than for prod) in Koin Android? #657

Closed NurseyitTursunkulov closed 4 years ago

NurseyitTursunkulov commented 4 years ago

I want to inject Koin in this project https://github.com/android/architecture-samples/tree/usecasesrename/app/src/main/java/com/example/android/architecture/blueprints/todoapp. They have a RealRepository for prod and FakeRepository for testing purposes. I can easily change modules in Application ` class MainApplication : Application() {

    override fun onCreate() {
    super.onCreate()

      startKoin {
    // module list
    modules(Repository())
    //modules(FakeRepository())
    }
 }

} ` but it is manual work and means that every time I want to run tests I have to substitute it here. Is there a way such depending on the use cases Koin would give me the right modules?

HarryMMR commented 4 years ago

Create a BaseTest that extends KoinTest. Inside it, you create another instance of startKoin with modules(FakeRepository())

Quentinvk commented 4 years ago

@NurseyitTursunkulov I'm working on the same project. Could you share your progress?

@HarryMMR They are complaining that it is not the right repository (org.koin.core.error.NoBeanDefFoundException: No definition found for 'ActualRepository' I tried this : @Test funshould inject my components`() { startKoin { modules( module { single { FakeRepository() } single { Application() } single { MainViewModel(get(), get()) } }) }

    // directly request an instance
    val fakeRepository = declareMock<FakeRepository>(){
        val task1 = Task("Title1", "Description1")
        val task2 = Task("Title2", "Description2", true)
        val task3 = Task("Title3", "Description3", true)
        tasksRepository.addTasks(task1, task2, task3)
    }
    assertNotNull(fakeRepository)
    assertEquals(fakeRepository, mainViewModel.repo)
}`

Sorry for this weird code, the quotes do not work as expected

NurseyitTursunkulov commented 4 years ago

Could you please show an example in a GitHub?