How to tell to HILT to inject implementation instead of interface, in the constructor

Viewed 17

I face to this problem when I try to code some test.

I have a repository class and an interface.

class ItemsRepository @Inject constructor(
    private val api: MercadoLibreApi
): IItemsRepository {
interface IItemsRepository {
    suspend fun getSearch(search: String): Resource<ResponseML>
}

a viewmodel class

@HiltViewModel
class MainViewModel @Inject constructor(
    val repo: ItemsRepository
    ) : ViewModel() {

and a Retrofit instance that is injected using Dagger/Hilt

    @Provides
    @Singleton
    fun providesMercadoLibreApi(retrofit: Retrofit): MercadoLibreApi {
        return retrofit.create(MercadoLibreApi::class.java)
    }

In my new MainViewModelTest class I want to create a mockedRepository instance.

private lateinit var itemsRepository : MockupItemsRepository

from this class:

class MockupItemsRepository: IItemsRepository { .. }

And then I want to use :

@Before
    fun setup() {
        viewModel = MainViewModel(itemsRepository)
    }

But I'm getting an error because "itemsRepository" is type MockupsItemsRepository and then I go to MainViewModel class, and change the parameter:

 val repo: IItemsRepository  //I'm using the interface

The error in MainViewModelTest dissapear, but I can't compile.

Hilt tells me thta I need a @Provides for the parameter:

IItemsRepository cannot be provided without an @Provides-annotated method

How to tell HILT that I want the implementation, not the interface?

Thanks for any idea, I may be doing too much trouble to test one method in the viewmodel ...

Best Regards

1 Answers

I found the solution, in this video from Mitch Tabian

https://codingwithmitch.com/courses/hilt-dependency-injection/modules-binds-and-provides/

In AppModule class I had to add the correct provider:

@Provides
@Singleton
fun providesItemsRepository(api: MercadoLibreApi): IItemsRepository = ItemsRepository(api)

I was confused and I was returning class ItemsRepository instead of the interface!

Some additional links:

https://medium.com/mobile-app-development-publication/dagger-2-binds-vs-provides-cbf3c10511b5

Best Regards

Related