我有一个视图模型,我使用 Hilt 向其中注入参数。
@HiltViewModel
class ShoppingViewModel @Inject constructor(
private val addIngredientUseCase: AddIngredientUseCase,
private val getIngredientsToBuyUseCase: GetIngredientsToBuyUseCase,
private val getLastBoughtIngredientsUseCase: GetLastBoughtIngedientsUseCase,
private val updateIngredientUseCase: UpdateIngredientUseCase,
private val deleteLastIngredientsUseCase: DeleteLastIngredientsUseCase
) : ViewModel() {...}
在主要活动中,我实例化它没有问题:
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
private val shoppingViewModel: ShoppingViewModel by viewModels()
[...]
}
说到测试,我无法实例化它。我该怎么做呢?
我尝试过:
@RunWith(AndroidJUnit4::class)
class ShoppingViewModelTest() {
@Mock
lateinit var addIngredientUseCase: AddIngredientUseCase
@Mock
lateinit var updateIngredientUseCase: UpdateIngredientUseCase
@Mock
lateinit var deleteLastIngredientsUseCase: DeleteLastIngredientsUseCase
@Mock
lateinit var getIngredientsToBuyUseCase: GetIngredientsToBuyUseCase
@Mock
lateinit var getLastIngredientsUseCase: GetLastBoughtIngedientsUseCase
private lateinit var shoppingViewModel: ShoppingViewModel
@Before
fun setUP(){
shoppingViewModel = ShoppingViewModel(addIngredientUseCase,getIngredientsToBuyUseCase,getLastIngredientsUseCase,updateIngredientUseCase,deleteLastIngredientsUseCase)
}
@Test
fun showDialogChangeTest(){
}
}
但我不知道如何初始化 Lateinit 属性。我应该做什么,因为每个用例都有其应该初始化的参数
我在官方文档中找到了解决方案。 我已经创建了班级
class CustomTestRunner:AndroidJUnitRunner() {
override fun newApplication(
cl: ClassLoader?,
className: String?,
context: Context?
): Application {
return super.newApplication(cl, HiltTestApplication::class.java.name, context)
}
并将以下几行添加到 build.gradle 文件中
android {
defaultConfig {
// Replace com.example.android.dagger with your class path.
testInstrumentationRunner "com.example.android.dagger.CustomTestRunner"
}
}
对于测试,我使用了 HiltAndroidTest 注释,它允许我注入参数(我在整个项目中都使用了 dagger hilt),如下所示:
@HiltAndroidTest
@Config(application = HiltTestApplication::class)
@RunWith(AndroidJUnit4::class)
class ShoppingViewModelTest() {
@get:Rule
var hiltRule = HiltAndroidRule(this)
@Inject
lateinit var addIngredientUseCase: AddIngredientUseCase
@Inject
lateinit var updateIngredientUseCase: UpdateIngredientUseCase
@Inject
lateinit var deleteLastIngredientsUseCase: DeleteLastIngredientsUseCase
@Inject
lateinit var getIngredientsToBuyUseCase: GetIngredientsToBuyUseCase
@Inject
lateinit var getLastIngredientsUseCase: GetLastBoughtIngedientsUseCase
private lateinit var shoppingViewModel:ShoppingViewModel
@Before
fun init(){
hiltRule.inject()
shoppingViewModel = ShoppingViewModel(addIngredientUseCase,getIngredientsToBuyUseCase,getLastIngredientsUseCase,updateIngredientUseCase,deleteLastIngredientsUseCase)
}
}