[英]How to tell to HILT to inject implementation instead of interface, in the constructor
I face to this problem when I try to code some test.当我尝试编写一些测试代码时,我遇到了这个问题。
I have a repository class and an interface.我有一个存储库 class 和一个接口。
class ItemsRepository @Inject constructor(
private val api: MercadoLibreApi
): IItemsRepository {
interface IItemsRepository {
suspend fun getSearch(search: String): Resource<ResponseML>
}
a viewmodel class视图模型 class
@HiltViewModel
class MainViewModel @Inject constructor(
val repo: ItemsRepository
) : ViewModel() {
and a Retrofit instance that is injected using Dagger/Hilt以及使用 Dagger/Hilt 注入的 Retrofit 实例
@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.在我的新 MainViewModelTest class 中,我想创建一个 mockedRepository 实例。
private lateinit var itemsRepository : MockupItemsRepository
from this class:从这个 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:但我收到一个错误,因为“itemsRepository”是 MockupsItemsRepository 类型,然后我将 go 更改为 MainViewModel class,然后更改参数:
val repo: IItemsRepository //I'm using the interface
The error in MainViewModelTest dissapear, but I can't compile. MainViewModelTest 中的错误消失了,但我无法编译。
Hilt tells me thta I need a @Provides for the parameter: Hilt 告诉我我需要一个 @Provides 作为参数:
IItemsRepository cannot be provided without an @Provides-annotated method
没有@Provides-annotated 方法就不能提供 IItemsRepository
How to tell HILT that I want the implementation, not the interface?如何告诉 HILT 我想要实现,而不是接口?
Thanks for any idea, I may be doing too much trouble to test one method in the viewmodel...感谢您的任何想法,我可能在视图模型中测试一种方法时太麻烦了......
Best Regards此致
I found the solution, in this video from Mitch Tabian我在 Mitch Tabian 的这段视频中找到了解决方案
https://codingwithmitch.com/courses/hilt-dependency-injection/modules-binds-and-provides/ https://codingwithmitch.com/courses/hilt-dependency-injection/modules-binds-and-provides/
In AppModule class I had to add the correct provider:在 AppModule class 我必须添加正确的提供者:
@Provides
@Singleton
fun providesItemsRepository(api: MercadoLibreApi): IItemsRepository = ItemsRepository(api)
I was confused and I was returning class ItemsRepository instead of the interface!我很困惑,我返回的是 class ItemsRepository 而不是界面!
Some additional links:一些额外的链接:
https://medium.com/mobile-app-development-publication/dagger-2-binds-vs-provides-cbf3c10511b5 https://medium.com/mobile-app-development-publication/dagger-2-binds-vs-provides-cbf3c10511b5
Best Regards此致
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.