0

I am using Hilt for DI in my project. I am trying write unit test cases for LiveData object, but it's not coming under coverage.

ViewModel

@HiltViewModel
class HealthDiagnosticsViewModel @Inject constructor(
    private var networkHelper: NetworkHelper
) : ViewModel() {

    var result = MutableLiveData<Int>()

    .....

}

My unit test class is as below:

HealthViewModelTest

@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)
    }
}

Test Cases are passed but it's not coming under method coverage.

Kunu
  • 5,078
  • 6
  • 33
  • 61

1 Answers1

0

I'll share with you the an example of my code that would solve your problem.

I'm usnig ViewModel with Dagger Hilt

  1. You don't have to use Robelectric, you can use MockK library.

  2. Replace your HiltRule with this Rule:

    @get:Rule

    var rule: TestRule = InstantTaskExecutorRule()

  3. This is my ViewModel class

using MockK, you can mock the networkHelper class without Hilt. So, your setup method will be like that:

lateinit var networkHelper: NetworkHelper
......
......
......
@Before
fun setUp() {
    networkHelper = mockk<NetworkHelper>()
    healthDiagnosticsViewModel = HealthDiagnosticsViewModel(networkHelper)
}

4)The most important part in your test is to Observe to the LiveData first.

@Test
fun testGetResult() {
    healthDiagnosticsViewModel.result.observeForever {}
    val result = healthDiagnosticsViewModel.result.value
    Assert.assertEquals(null, result)
}

You can observe to the livedata for each unit test, but keep in mind to Observe first before change data.

MustafaKhaled
  • 1,343
  • 9
  • 25