This is a simple way to mock runtime dependencies in Instrumentation tests when using Koin Library
First, let’s take a look at how an application would mostly be set up when using Koin for DI.
This code will not compile, this is only for a simple run through.
Now as an example, let’s take a look at some UI code that consumes these dependencies and for which we will write some Espresso tests.
In the above activity, HomeViewModel
is lazy injected using an extension function provided by Koin.
We are observing a LiveData
returned by this HomeViewModel
and displaying the UI based on the value of Result
.
For the uninitiated, Result
is just a wrapper class used to hold different types of values like data, exceptions, etc. in the same object itself. You can find detailed info here.
Assuming that our HomeViewModel
and HomeInteractor
code is as follows:
Now to mock these dependencies in our instrumentation test, we need to add the below dependencies:
androidTestImplementation "org.koin:koin-test:2.x.x"androidTestImplementation "org.mockito:mockito-android:2.22.0"
Note: Since classes in Kotlin are final by default, it won’t be possible to mock them in instrumentation tests by Mockito. A simple and naive way to get around this will be to open the class but a better alternative can be found here or here
Mocking/Spying in Test Class
To mock the dependencies injected by Koin, we extend the KoinTest
class and override the module with the mocked dependency like below:
There may be some scenarios where instead of mocking the whole class, we would like to just mock a part of the real implementation.
In such a case, we first fetch the original dependency from Koin and create a spy of it, then override it with this spy.
Mocking in Test Application
On the off chance that we want to override a dependency throughout the test application, then instead of overriding the dependencies in every test class, we can just do it once by extending the Application class in the androidTest
directory like
and to wrap this up we have to create a custom runner and add it to our build.gradle
file
References