Hi all :android-wave:, How to write UT for logic i...
# compose-android
a
Hi all 👋, How to write UT for logic inside Composables? For stateless UI composables, I can cover them using compose testing. But, for a stateful composable, how can I test the logic? Sample code in 🧵 .
Example
Copy code
@Composable
fun HomeScreen() {
  var state1 by remember {
        mutableStateOf(
            value = "First Name",
        )
  }

  var state2 by remember {
        mutableStateOf(
            value = 123,
        )
  }

  val combinedState = remember(state1, state2) {
    // Some logic which creates a new state by processing the existing states.
  }
}
In this case, How to test the logic added here?
Copy code
// Some logic which creates a new state by processing the existing states.
One option I can think of is to extract the code into a top level function outside the
HomeScreen
composable and test it. I would like to know if there are better approaches to structure and test this code. thank you color
z
Ideally, hoist the state to make the caller own it and make your component stateless. Otherwise, you’d need to interact with the component via semantics or other input events.
a
This is the top most screen level composable.
This composable is only for the state handling. All UI is rendered using a child composable which is completely stateless.
z
Sounds like that stuff should be in a view model or presenter or something, not a composable
a
Do you mean I can not have states in Composable 🤔? Any reason to hoist all UI states in the ViewModel if the view model does not require the state?
z
That’s not what I mean, you can definitely have state in composables. But if you have a bunch of business logic that drives your view layer, and you want to test it separately, that is the whole reason for separating the presentation/view model as a separate architectural layer from the view layer. All these architectural patterns basically exist to solve this problem.
👍 2
☝️ 1