https://kotlinlang.org logo
#android
Title
# android
a

amrita

10/04/2023, 3:18 PM
I am running into an issue when running the UI test for a compose component. The error is "Cannot create an instance of class ........ViewModel". The component is like this
Copy code
@Composable
fun ExampleView(
    navController: NavController,
    testViewModel: TestViewModel = hiltViewModel()
) {}
Here is how I am calling from the test of this component.
Copy code
class ExampleViewTest {

    @get:Rule
    val composeTestRule = createComposeRule()

    @Test
    fun test_exampleView() {
        val navController = TestNavHostController(
            ApplicationProvider.getApplicationContext()
        )

        composeTestRule.setContent {
            ExampleView(navController = navController)
        }
    }
}
Here is the TestViewModel set up
Copy code
@HiltViewModel
class TestViewModel @Inject constructor(
    private val testRepo: TestRepo
) : ViewModel() {
}
c

Chrimaeon

10/04/2023, 5:23 PM
Just pass in the view model as you pass the nav controller. So do „manual“ dependency injection. That’s why you define it as a default parameter - so you can „override“ it in your test. Hilt will not work in a unit test. I think there is something like a hilt rule where you can build a test dependency tree but I’ve never used .
a

amrita

10/04/2023, 6:17 PM
can you please explain more? I am really new to jetpack compose as well as it's UI testing.
c

Chrimaeon

10/04/2023, 6:23 PM
I think that’s out of the context for this workspace. Your lack in knowledge is not testing but dependency injection in general. I think I gave you enough hints to look for Medium articles. Also have a look at all the google compose sample apps. They all have test and do manual dependency injection in there.
thank you color 1
s

Sam

10/04/2023, 9:28 PM
Seen your follow up in the chat. Christian is spot on in what he's suggesting, essentially you need to create an instance of your ViewModel in your test (or perhaps a mock/dummy/fake instance) and pass that through to your view, not using the default value 🙂
thank you color 1
2 Views