0

I'm trying to make some tests and i need to replace the real dependency by a fake one by overriding it on KODEIN but it's not working and i don't know what i can do anymore.

Here is my dependency graph (I'm omitting others dependencies):

class Injector(private val context: Context) {

    val dependencies = Kodein.lazy {

        .
        .
        bind<RetrieveContacts>() with provider {
            Log.i("RetrieveContacts","REAL")
            RetrieveContactsInMemory()
        }
        .
        .     
    }
}

Here is my application class:

class AppApplication : Application(), KodeinAware {

   override val kodein by Injector(this).dependencies
}

Here is what i'm doing to override the dependency:

@RunWith(value = AndroidJUnit4::class)
class HomeActivityEmptyStateTest {

    @get:Rule
    var mActivityTestRule = ActivityTestRule<HomeActivity>(HomeActivity::class.java)

    @Before
    fun setup() {

        val appApplication = InstrumentationRegistry.getInstrumentation().targetContext

        val kodein by Kodein.lazy {

            extend(appApplication.appKodein())

            bind<RetrieveContacts>(overrides = true) with provider {
                Log.i("RetrieveContacts","FAKE")
                RetrieveEmptyContacts()
            }
        }
    }

    @Test
    fun testWhenHasNoContent() {
        ...
    }

}

I'm still seeing "RetrieveContacts REAL" instead of "RetrieveContacts FAKE" in console log

Rodrigohsb
  • 11
  • 3

2 Answers2

1

It seems like you forgot to allow overrides when extending in your test.

extend(appApplication.appKodein(), allowOverride = true)
avolkmann
  • 2,962
  • 2
  • 19
  • 27
0

This does not work since the parents definition will not be overridden. more info: https://kodein.org/Kodein-DI/?6.1/core#_overridden_access_from_parent

This is because Bar is bound to a singleton, the first access would define the container used (parent or child). If the singleton were initialized by child, then a subsequent access from parent would yeild a Bar with a reference to a Foo2, which is not supposed to exist in parent.

Maurycy
  • 3,911
  • 8
  • 36
  • 44