https://kotlinlang.org logo
#android
Title
# android
n

Nikola Milovic

11/18/2019, 9:05 AM
Dagger2, tests fail because lateinit not initialized
Copy code
@Module(includes = [TestApplicationModuleBinds::class])
object TestApplicationModule {
    @set:Inject
    lateinit var mockQuoteDataSource : MockQuoteDataSource
Copy code
class MockQuoteDataSource @Inject constructor(jsonNetworkService: JsonNetworkService) : TestQuoteRemoteDataSource(jsonNetworkService.apiService) {
I get the error
Copy code
kotlin.UninitializedPropertyAccessException: lateinit property mockQuoteDataSource has not been initialized
t

tseisel

11/18/2019, 9:29 AM
Why are you injecting to a field in a module object class ?
n

Nikola Milovic

11/18/2019, 9:32 AM
Copy code
@Test
    fun willDisplayQuote() {
        TestApplicationModule.mockQuoteDataSource.mockSuccess(listOf(Quote("Expected Author", "Expected Quote")))
I'm trying to use the mockQuoteDataSource in my tests, should i move it all together somewhere else?
t

tseisel

11/18/2019, 10:22 AM
You should not inject into `Module`s. In fact, Dagger modules should only be used to provide types that you don't own, for example the application
Context
or
SharedPreferences
, and you should avoid instance fields in modules (especially if those are
object
). I think you need a
Component
. Depending on the type of test you are writing, you should proceed the following : - Unit Tests : just don't use Dagger. Instantiate the class under test yourself, passing its dependencies as mocks or fakes. - Integration Tests : create a Dagger
Component
responsible for instantiating the class under test with its real dependencies. This component should reference alternative version of the production `Module`s, for example simulating a network API or using an in-memory database. More information here : https://dagger.dev/testing
n

Nikola Milovic

11/18/2019, 10:23 AM
Thank you, I will check it out! I've been struggling for a while with this
3 Views