I have some Android instrumentation tests and a de...
# koin
p
I have some Android instrumentation tests and a dependency declared in a module. In most of our tests, we want the normal dependency. But in one test file, we want to inject a mock version of the dependency. What's the best way to inject a mock dependency and then make sure to replace it with the normal dependency after the tests in that file are complete?
m
Hey Peter (long time no see) 👋 - if you call
loadKoinModules
with a module that’s been instantiated with
override = true
that has a dependency with the same type, it should override any modules that have already been loaded
so you could set up a JUnit rule or something to load your override module before tests and unload it after
a
from koin-test you have also
declareMock
API
to override a current def wih a mocked one
m
ah yeah I think I never got in the habit of using
declareMock
because I set up something as I described above before you added the
MockProviderRule
which decoupled the library from mockito
p
And Hi @Matt Thompson! Great to hear from you again!
Because Android instrumentation tests call our application's onCreate, koin has already been started by the time our test file starts running tests. I've found it hard to load in a specific mocked dependency in a single test file and then replace it afterwards because I can't call startKoin again. Will
declareMock
help with this?
m
hm yeah I’m not sure there’s anything that will automatically remove the declaration for you - all I’m seeing from
DeclareMock.kt
is that it instantiates the mock via your mockprovider and adds it to your definitions. might have to stick with
loadKoinModules
and
unloadKoinModules
for tests that don’t start/stop koin
p
The real solution here is the Android team should fix the test orchestrator on Android 11 so I don't have to worry about unloading test Koin modules interfering with other instrumentation tests https://github.com/android/android-test/issues/743
💡 1