[英]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.