Koin: Use Koin injection inside Spek tests

Created on 12 Oct 2018  ·  3Comments  ·  Source: InsertKoinIO/koin

Hey,
I'm relative new in the topic of DI and I started to use koin with android development. I also want to write test with the Spek framework because I like the idea to write tests in BDD-Style.
I'm asking my self how I can inject something inside a Spek class? Or is it even possible to inject stuff inside tests without using koin-test?

question

Most helpful comment

@arnaudgiuliani @AHarazim
Hey,
How I can inject object inside a Spek Test class?
Please share code snipets:bow:

class MainViewModelTest: Spek({

    beforeEachTest {
        startKoin {
            androidContext(mockedApplication)
            modules(module {
                arrayOf(appModule, netModule, viewModelModule, repositoryModule)
            })
        }
    }
    afterGroup {
        stopKoin()
    }

    val repository: DataRepository by inject() ← Unresolved reference 
    val viewModel: MainViewModel by viewModel() ← Unresolved reference

    describe("") {
        context("") {

            it("") {
                viewModel.listLiveData.observeForever {

                }
                Assert.assertEquals(1, 1)
            }
        }
    }
})

All 3 comments

You can just use the koin-core package to have the KoinComponent interface tag & startKoin() function. The koin-test will add you declareMock & checkModules functions.

@arnaudgiuliani Works! Thx a lot!

@arnaudgiuliani @AHarazim
Hey,
How I can inject object inside a Spek Test class?
Please share code snipets:bow:

class MainViewModelTest: Spek({

    beforeEachTest {
        startKoin {
            androidContext(mockedApplication)
            modules(module {
                arrayOf(appModule, netModule, viewModelModule, repositoryModule)
            })
        }
    }
    afterGroup {
        stopKoin()
    }

    val repository: DataRepository by inject() ← Unresolved reference 
    val viewModel: MainViewModel by viewModel() ← Unresolved reference

    describe("") {
        context("") {

            it("") {
                viewModel.listLiveData.observeForever {

                }
                Assert.assertEquals(1, 1)
            }
        }
    }
})
Was this page helpful?
0 / 5 - 0 ratings

Related issues

LukasAnda picture LukasAnda  ·  3Comments

caleb-allen picture caleb-allen  ·  4Comments

ILAgent picture ILAgent  ·  3Comments

congtuyenvip picture congtuyenvip  ·  4Comments

fmobus picture fmobus  ·  4Comments