[英]How to tell to HILT to inject implementation instead of interface, in the constructor
当我尝试编写一些测试代码时,我遇到了这个问题。
我有一个存储库 class 和一个接口。
class ItemsRepository @Inject constructor(
private val api: MercadoLibreApi
): IItemsRepository {
interface IItemsRepository {
suspend fun getSearch(search: String): Resource<ResponseML>
}
视图模型 class
@HiltViewModel
class MainViewModel @Inject constructor(
val repo: ItemsRepository
) : ViewModel() {
以及使用 Dagger/Hilt 注入的 Retrofit 实例
@Provides
@Singleton
fun providesMercadoLibreApi(retrofit: Retrofit): MercadoLibreApi {
return retrofit.create(MercadoLibreApi::class.java)
}
在我的新 MainViewModelTest class 中,我想创建一个 mockedRepository 实例。
private lateinit var itemsRepository : MockupItemsRepository
从这个 class:
class MockupItemsRepository: IItemsRepository { .. }
然后我想使用:
@Before
fun setup() {
viewModel = MainViewModel(itemsRepository)
}
但我收到一个错误,因为“itemsRepository”是 MockupsItemsRepository 类型,然后我将 go 更改为 MainViewModel class,然后更改参数:
val repo: IItemsRepository //I'm using the interface
MainViewModelTest 中的错误消失了,但我无法编译。
Hilt 告诉我我需要一个 @Provides 作为参数:
没有@Provides-annotated 方法就不能提供 IItemsRepository
如何告诉 HILT 我想要实现,而不是接口?
感谢您的任何想法,我可能在视图模型中测试一种方法时太麻烦了......
此致
我在 Mitch Tabian 的这段视频中找到了解决方案
https://codingwithmitch.com/courses/hilt-dependency-injection/modules-binds-and-provides/
在 AppModule class 我必须添加正确的提供者:
@Provides
@Singleton
fun providesItemsRepository(api: MercadoLibreApi): IItemsRepository = ItemsRepository(api)
我很困惑,我返回的是 class ItemsRepository 而不是界面!
一些额外的链接:
https://medium.com/mobile-app-development-publication/dagger-2-binds-vs-provides-cbf3c10511b5
此致
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.