https://kotlinlang.org logo
Title
a

Abhinav Sharma

11/19/2021, 9:13 AM
Hello, I am trying to write screenshot tests for
HorizontalTrayUi()
and
TrayItemUi()
Its easy to test
TrayItemUi()
in isolation by mocking
TrayItemViewModel
and its exposed state flows, but whats the recommended way to test
HorizontalTrayUi()
as it calls
TrayItemUi()
which then tries to create a viewModel using
Hilt
Here’s the structure
@Composable
fun HorizontalTrayUi(
	trayModel: TrayModle,
	viewModel: TrayViewModel = viewModel()
) {
	Text(...) // title of the tray
	LazyRow(..){
		item -> {
			TrayItemUi(item)
		}
	}
}
@Composable
fun TrayItemUi(
	item: TrayItemModel,
	viewModel: TrayItemViewModel = viewModel()
) {
	......
}
@Pedro Gomez
p

Pedro Gomez

11/19/2021, 10:01 AM
Assume the screenshot testing library will take the screenshot of what's shown on the screen. No matter how many composable views you have inside. If A depends on B and you render A. Your screenshot will show A and B. If you only render B, A will be out of the screenshot scope. If you want to use test doubles you'll need to pass the view model from the HorizontalTrayUi even if it's used inside TrayItemUi. Looking at the code I think you'll have to modify HorizontalTrayUi API to receive the TrayItemViewModel instances or a factory. Dependency injectors are quite handy for this. You have some examples here: https://github.com/Karumi/KataSuperHeroesCompose
:thank-you: 1
a

Abhinav Sharma

11/19/2021, 10:25 AM
Thanks, I will try using Hilt in tests for injecting TrayItemViewModel — sounds like a good idea But getting TrayItemViewModel in HorizontalTrayUi() — isn’t sounding good as Composables can be nested to any level and just for tests I cannot pull all viewmodels in root composable methods.. But thanks for the idea - going to dig into Hilt usage for Tests..
p

Pedro Gomez

11/22/2021, 11:57 PM
yeap, that's why dependency injection is so useful 🙂