https://kotlinlang.org logo
#koin
Title
# koin
m

Mohsen

10/25/2023, 9:21 PM
Hello, team! Question: How can I fix this error in unit testing with Koin?
No definition found for type 'com.client.githubusers.data.repository.UsersRepositoryImpl'.
Impl:
Copy code
class UsersRepositoryTest : KoinTest {

    private val usersRepository: UsersRepository by inject<UsersRepositoryImpl>()

    @OptIn(ExperimentalCoroutinesApi::class)
    private val testScope = TestScope(UnconfinedTestDispatcher())
    private val usersStub = StubUtil.getDummyUsers()
    private val userDetailStub = StubUtil.getDummyUserDetail()

    @Before
    fun setup() {
        startKoin {
            modules(
                module {
                    single<UsersRepository> { UsersRepositoryImpl(get()) }
                })
        }
    }
What am I doing wrong here?
👍 1
m

mkrussel

10/25/2023, 9:32 PM
The single is for type
UserRepository
, but the inject is looking for
UserRepositoryImpl
.
m

Mohsen

10/25/2023, 9:37 PM
Well, that’s true. How can we solve that?
m

mkrussel

10/25/2023, 9:38 PM
Make them the same type based on what you need for the test.
1
m

Mohsen

10/25/2023, 9:40 PM
It says: Could not create instance for ’[Singleton:‘com.client.githubusers.data.repository.UsersRepositoryImpl’]'
Copy code
private val usersRepository: UsersRepositoryImpl by inject()
And:
Copy code
single { UsersRepositoryImpl(get()) }
Maybe I am missing something?
m

mkrussel

10/25/2023, 9:41 PM
I don't know. What is the
get
in the constructor call supposed to return and is that available? I doesn't seem like it would be since there is only one module and one item in the module, but my koin knowledge is very limited.
m

Mohsen

10/25/2023, 9:43 PM
It’s an interface in the constructor - just for retrofit purposes.
m

mkrussel

10/25/2023, 9:44 PM
Where is koin supposed to get an instance of that interface?
m

Mohsen

10/25/2023, 9:46 PM
Good point. I missed that. So now I have:
Copy code
private val usersRepository: UsersRepositoryImpl by inject()
private val usersApi: UsersApi by inject()

module {
    single { UsersRepositoryImpl(usersApi) }
})
Sorry for the noob questions, I just started using it in testing.
m

mkrussel

10/25/2023, 9:47 PM
But the inject still cannot find it because it is not in your module. You need to create an instance of the api somewhere, just like you do in the app.
I think you need to add another
single
to your module. And either create a fake instance of the api or add more code that initializes retrofit to be able to create the real version of the api.
1