我在我的项目中使用 Hilt 进行 DI。我正在尝试为 LiveData 对象编写单元测试用例,但它没有被覆盖。
视图模型
@HiltViewModel
class HealthDiagnosticsViewModel @Inject constructor(
private var networkHelper: NetworkHelper
) : ViewModel() {
var result = MutableLiveData<Int>()
.....
}
我的单元测试类如下:
健康视图模型测试
@HiltAndroidTest
@RunWith(RobolectricTestRunner::class)
@Config(application = HiltTestApplication::class)
class HealthDiagnosticsViewModelTest{
@get:Rule
var hiltRule = HiltAndroidRule(this)
@Inject
lateinit var networkHelper: NetworkHelper
lateinit var healthDiagnosticsViewModel: HealthDiagnosticsViewModel
@Before
fun setUp() {
hiltRule.inject()
healthDiagnosticsViewModel = HealthDiagnosticsViewModel(networkHelper)
}
@Test
fun testGetResult() {
val result = healthDiagnosticsViewModel.result.value
Assert.assertEquals(null, result)
}
@Test
fun testSetResult() {
healthDiagnosticsViewModel.result.value = 1
Assert.assertEquals(1, healthDiagnosticsViewModel.result.value)
}
}
测试用例已通过,但它不在方法覆盖范围内。