Dagger2, tests fail because lateinit not initializ...
# android
n
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
Why are you injecting to a field in a module object class ?
n
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
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
Thank you, I will check it out! I've been struggling for a while with this