Are there any examples of using Koin in a Jetpack ...
# koin
j
Are there any examples of using Koin in a Jetpack Compose test (as described in https://developer.android.com/codelabs/jetpack-compose-testing) ...for example being able to inject mock dependencies?
hmm, I guess same approach used for "normal" instrumentation tests should work here as well e.g. calling
loadKoinModules
r
Could also just hoist your koin dependencies and manually pass fakes as parameters in tests
j
Yeah, was thinking along those lines as well. Right now I have screen level composables and it's those where I'm using Koin to inject view model.....they then pass down data to lower level ones and they can certainly be tested like that. I'd potentially need to inject view model instead in "main layout" composable where I have
NavHost
for example and observe/pass down from there the different pieces of data that the screen level ones need. Can certainly do that but it feels like they become somewhat less encapsulated than before.
this is example from one of the official compose samples (using Hilt in that case)
Copy code
@Composable
fun CalendarScreen(
    onBackPressed: () -> Unit,
    calendarViewModel: CalendarViewModel = viewModel()
) {
trying same thing here with Koin and seems to work well
Copy code
@Composable
fun PersonListScreen(paddingValues: PaddingValues,
     personSelected: (person: Assignment) -> Unit,
     peopleInSpaceViewModel: PeopleInSpaceViewModel = getViewModel()
) {
can write compose test like following then....but def open to better ways of doing any of this
Copy code
@Test
fun testGetPeople() {
    val peopleInSpaceRepository = PeopleInSpaceRepositoryFake()
    val peopleInSpaceViewModel = PeopleInSpaceViewModel(peopleInSpaceRepository)
    composeTestRule.setContent {
        PersonListScreen(
            paddingValues = PaddingValues(),
            personSelected = {},
            peopleInSpaceViewModel = peopleInSpaceViewModel
        )
    }
    composeTestRule
        .onNodeWithText("Megan McArthur")
        .assertIsDisplayed()
}
a
With koin-test, you also have the
declare
API to replace a definition with a Mock one if you need
👍 1