Android fragmentscenario need to click on a compose button - android

This is my code for trying to interact with a compose view in a fragment
class Test{
#get:Rule
var composeTestRule = createAndroidComposeRule<ComponentActivity>()
#Test
fun test() {
val scenario = launchFragmentInContainer(themeResId = R.style.AppTheme) {
val args = TestFragmentArgs(
"test parameter"
)
TestFragment().also { fragment ->
fragment.viewLifecycleOwnerLiveData.observeForever { viewLifecycleOwner ->
viewLifecycleOwner?.let {
val viewModelStore = ViewModelStore()
navController.setViewModelStore(viewModelStore)
navController.setGraph(R.navigation.nav_graph)
navController.setCurrentDestination(
R.id.fragment_to_test,
args = args.toBundle()
)
Navigation.setViewNavController(
fragment.requireView(),
navController
)
fragment.arguments = args.toBundle()
}
}
}
onView(withId(R.id.header)).check(matches(isDisplayed())) // passes
composeTestRule.apply {
onNodeWithTag("TextInput").performTextInput("11214") // fails
}
}
}
}
When I try to interact with any of the compose able views I get an error stating that
"No compose hierarchies found in the app"
Another thing I noticed is that the compose view doesn't show up until the test fails

Related

Navigate in compose based on result

I've this screen:
#Composable
fun SetNewPasswordScreen(
viewModel: SetNewPasswordViewModel,
navigateToSetDetails: () -> Unit,
) {
val state by viewModel.state.collectAsState()
if (state.passwordConfirmed) {
LaunchedEffect(Unit) {
navigateToSetDetails()
}
} else {
SetNewPasswordScreen(
confirmNewPassword = viewModel::confirmNewPassword
)
}
}
and this is the view model:
#HiltViewModel
class SetNewPasswordViewModel #Inject constructor(
private val setNewPassword: SetNewPassword,
) : ViewModel() {
val state: StateFlow<SetNewPasswordViewState> = setNewPassword.flow
.map { hasSetNewPassword ->
SetNewPasswordViewState(passwordConfirmed = hasSetNewPassword)
}
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(),
initialValue = SetNewPasswordViewState.Empty
)
fun confirmNewPassword(newPassword: String, repeatedNewPassword: String) {
viewModelScope.launch {
setNewPassword(SetNewPassword.Params(newPassword, repeatedNewPassword))
}
}
}
My problem is when I try to navigate back from
SetDetailsScreen
to
SetNewPasswordScreen
I'm getting true for state.passwordConfirmed again, and I'm stuck in a loop.
I've thought about resetting passwordConfirmed right after the if statement, or using previousBackStackEntry in SetDetailsScreen to store that password should be confirmed again, but it doesn't seem right to do so every time I want to navigate back to a screen that got a result. What's the best practice for this kind of situation?

How to test ViewModel + Flow

I'm doing a small project to learn flow and the latest Android features, and I'm currently facing the viewModel's testing, which I don't know if I'm performing correctly. can you help me with it?
Currently, I am using a use case to call the repository which calls a remote data source that gets from an API service a list of strings.
I have created a State to control the values in the view model:
data class StringItemsState(
val isLoading: Boolean = false,
val items: List<String> = emptyList(),
val error: String = ""
)
and the flow:
private val stringItemsState = StringtemsState()
private val _stateFlow = MutableStateFlow(stringItemsState)
val stateFlow = _stateFlow.asStateFlow()
and finally the method that performs all the logic in the viewModel:
fun fetchStringItems() {
try {
_stateFlow.value = stringItemsState.copy(isLoading = true)
viewModelScope.launch(Dispatchers.IO) {
val result = getStringItemsUseCase.execute()
if (result.isEmpty()) {
_stateFlow.value = stringItemsState
} else {
_stateFlow.value = stringItemsState.copy(items = result)
}
}
} catch (e: Exception) {
e.localizedMessage?.let {
_stateFlow.value = stringItemsState.copy(error = it)
}
}
}
I am trying to perform the test following the What / Where / Then pattern, but the result is always an empty list and the assert verification always fails:
private val stringItems = listOf<String>("A", "B", "C")
#Test
fun `get string items - not empty`() = runBlocking {
// What
coEvery {
useCase.execute()
} returns stringItems
// Where
viewModel.fetchStringItems()
// Then
assert(viewModel.stateFlow.value.items == stringItems)
coVerify(exactly = 1) { viewModel.fetchStringItems() }
}
Can someone help me and tell me if I am doing it correctly? Thanks.

Unit testing Android ViewModel with a StateFlow that mapsLatest from another StateFlow but the mapLatest is never triggered

So I have a ViewModel I'm trying to unit test. It is using the stateIn operator. I found this documentation about how to test stateflows created using the stateIn operator https://developer.android.com/kotlin/flow/test but the mapLatest never triggers even though I'm collecting the flow.
class DeviceConfigurationViewModel(
val systemDetails: SystemDetails,
val step: AddDeviceStep.ConfigureDeviceStep,
val service: DeviceRemoteService
) : ViewModel(), DeviceConfigurationModel {
#OptIn(ExperimentalCoroutinesApi::class)
private val _state: StateFlow<DeviceConfigurationModel.State> =
service.state
.mapLatest { state ->
when (state) {
DeviceRemoteService.State.Connecting -> {
DeviceConfigurationModel.State.Connecting
}
is DeviceRemoteService.State.ConnectedState.Connected -> {
state.sendCommand(step.toCommand(systemDetails))
DeviceConfigurationModel.State.Connected
}
is DeviceRemoteService.State.ConnectedState.CommandSent -> {
DeviceConfigurationModel.State.Configuring
}
is DeviceRemoteService.State.ConnectedState.MessageReceived -> {
transformMessage(state)
}
is DeviceRemoteService.State.Disconnected -> {
transformDisconnected(state)
}
}
}
.distinctUntilChanged()
.stateIn(
viewModelScope,
SharingStarted.WhileSubscribed(5000), // Keep it alive for a bit if the app is backgrounded
DeviceConfigurationModel.State.Disconnected
)
override val state: StateFlow<DeviceConfigurationModel.State>
get() = _state
private fun transformDisconnected(
state: DeviceRemoteService.State.Disconnected
): DeviceConfigurationModel.State {
return if (state.hasCause) {
DeviceConfigurationModel.State.UnableToConnect(state)
} else {
state.connect()
DeviceConfigurationModel.State.Connecting
}
}
private fun transformMessage(state: DeviceRemoteService.State.ConnectedState.MessageReceived): DeviceConfigurationModel.State {
return when (val message = state.message) {
is Message.AddedToProject -> DeviceConfigurationModel.State.Configured
is Message.ConfigWifiMessage -> {
if (!message.values.success) {
DeviceConfigurationModel.State.Error(
message.values.errorCode,
state,
step.toCommand(systemDetails)
)
} else {
DeviceConfigurationModel.State.Configuring
}
}
}
}
}
And here's my unit test. The mapLatest never seems to get triggered even though I'm collecting the flow. I'm using the suggestions here https://developer.android.com/kotlin/flow/test
#OptIn(ExperimentalCoroutinesApi::class)
class DeviceConfigurationViewModelTest {
private val disconnectedService = mock<DisconnectedService>()
private val deviceServiceState: MutableStateFlow<DeviceRemoteService.State> =
MutableStateFlow(DeviceRemoteService.State.Disconnected(disconnectedService, Exception()))
private val deviceService = mock<DeviceRemoteService> {
on { state } doReturn deviceServiceState
}
private val systemDetails = mock<SystemDetails> {
on { controllerAddress } doReturn "192.168.1.112"
on { controllerName } doReturn "000FFF962FE7"
}
private val step = AddDeviceDeviceStep.ConfigureDeviceStep(
44,
"Thou Shalt Not Covet Thy Neighbor’s Wifi",
"testing616"
)
private lateinit var viewModel: DeviceConfigurationViewModel
#Before
fun setup() {
viewModel = DeviceConfigurationViewModel(systemDetails, step, deviceService)
}
#Test
fun testDeviceServiceDisconnectWithCauseMapsToUnableToConnect() =
runTest {
val collectJob = launch(UnconfinedTestDispatcher()) { viewModel.state.collect() }
deviceServiceState.emit(
DeviceRemoteService.State.Disconnected(Exception("Something bad happened"))
)
assertThat(viewModel.state.value).isInstanceOf(DeviceConfigurationModel.State.UnableToConnect::class.java)
collectJob.cancel()
}
}
I believe this is happening because the viewModelScope uses a hardcoded Main dispatcher under the hood.
You can follow the instructions here in the Android documentation to see how you can to set the Main dispatcher for tests.

Android Compose with single event

Right now I have an Event class in the ViewModel that is exposed as a Flow this way:
abstract class BaseViewModel() : ViewModel() {
...
private val eventChannel = Channel<Event>(Channel.BUFFERED)
val eventsFlow = eventChannel.receiveAsFlow()
fun sendEvent(event: Event) {
viewModelScope.launch {
eventChannel.send(event)
}
}
sealed class Event {
data class NavigateTo(val destination: Int): Event()
data class ShowSnackbarResource(val resource: Int): Event()
data class ShowSnackbarString(val message: String): Event()
}
}
And this is the composable managing it:
#Composable
fun SearchScreen(
viewModel: SearchViewModel
) {
val events = viewModel.eventsFlow.collectAsState(initial = null)
val snackbarHostState = remember { SnackbarHostState() }
val coroutineScope = rememberCoroutineScope()
Box(
modifier = Modifier
.fillMaxHeight()
.fillMaxWidth()
) {
Column(
modifier = Modifier
.padding(all = 24.dp)
) {
SearchHeader(viewModel = viewModel)
SearchContent(
viewModel = viewModel,
modifier = Modifier.padding(top = 24.dp)
)
when(events.value) {
is NavigateTo -> TODO()
is ShowSnackbarResource -> {
val resources = LocalContext.current.resources
val message = (events.value as ShowSnackbarResource).resource
coroutineScope.launch {
snackbarHostState.showSnackbar(
message = resources.getString(message)
)
}
}
is ShowSnackbarString -> {
coroutineScope.launch {
snackbarHostState.showSnackbar(
message = (events.value as ShowSnackbarString).message
)
}
}
}
}
SnackbarHost(
hostState = snackbarHostState,
modifier = Modifier.align(Alignment.BottomCenter)
)
}
}
I followed the pattern for single events with Flow from here.
My problem is, the event is handled correctly only the first time (SnackBar is shown correctly). But after that, seems like the events are not collected anymore. At least until I leave the screen and come back. And in that case, all events are triggered consecutively.
Can't see what I'm doing wrong. When debugged, events are sent to the Channel correctly, but seems like the state value is not updated in the composable.
Rather than placing your logic right inside composable place them inside
// Runs only on initial composition
LaunchedEffect(key1 = Unit) {
viewModel.eventsFlow.collectLatest { value ->
when(value) {
// Handle events
}
}
}
And also rather than using it as state just collect value from flow in LaunchedEffect block. This is how I implemented single event in my application
Here's a modified version of Jack's answer, as an extension function following new guidelines for safer flow collection.
#Composable
inline fun <reified T> Flow<T>.observeWithLifecycle(
lifecycleOwner: LifecycleOwner = LocalLifecycleOwner.current,
minActiveState: Lifecycle.State = Lifecycle.State.STARTED,
noinline action: suspend (T) -> Unit
) {
LaunchedEffect(key1 = Unit) {
lifecycleOwner.lifecycleScope.launch {
flowWithLifecycle(lifecycleOwner.lifecycle, minActiveState).collect(action)
}
}
}
Usage:
viewModel.flow.observeWithLifecycle { value ->
//Use the collected value
}
I'm not sure how you manage to compile the code, because I get an error on launch.
Calls to launch should happen inside a LaunchedEffect and not composition
Usually you can use LaunchedEffect which is already running in the coroutine scope, so you don't need coroutineScope.launch. Read more about side effects in documentation.
A little kotlin advice: when using when in types, you don't need to manually cast the variable to a type with as. In cases like this, you can declare val along with your variable to prevent Smart cast to ... is impossible, because ... is a property that has open or custom getter error:
val resources = LocalContext.current.resources
val event = events.value // allow Smart cast
LaunchedEffect(event) {
when (event) {
is BaseViewModel.Event.NavigateTo -> TODO()
is BaseViewModel.Event.ShowSnackbarResource -> {
val message = event.resource
snackbarHostState.showSnackbar(
message = resources.getString(message)
)
}
is BaseViewModel.Event.ShowSnackbarString -> {
snackbarHostState.showSnackbar(
message = event.message
)
}
}
}
This code has one problem: if you send the same event many times, it will not be shown because LaunchedEffect will not be restarted: event as key is the same.
You can solve this problem in different ways. Here are some of them:
Replace data class with class: now events will be compared by pointer, not by fields.
Add a random id to the data class, so that each new element is not equal to another:
data class ShowSnackbarResource(val resource: Int, val id: UUID = UUID.randomUUID()) : Event()
Note that the coroutine LaunchedEffect will be canceled when a new event occurs. And since showSnackbar is a suspend function, the previous snackbar will be hidden to display the new one. If you run showSnackbar on coroutineScope.launch (still doing it inside LaunchedEffect), the new snackbar will wait until the previous snackbar disappears before it appears.
Another option, which seems cleaner to me, is to reset the state of the event because you have already reacted to it. You can add another event to do this:
object Clean : Event()
And send it after the snackbar disappears:
LaunchedEffect(event) {
when (event) {
is BaseViewModel.Event.NavigateTo -> TODO()
is BaseViewModel.Event.ShowSnackbarResource -> {
val message = event.resource
snackbarHostState.showSnackbar(
message = resources.getString(message)
)
}
is BaseViewModel.Event.ShowSnackbarString -> {
snackbarHostState.showSnackbar(
message = event.message
)
}
null, BaseViewModel.Event.Clean -> return#LaunchedEffect
}
viewModel.sendEvent(BaseViewModel.Event.Clean)
}
But in this case, if you send the same event while the previous one has not yet disappeared, it will be ignored as before. This can be perfectly normal, depending on the structure of your application, but to prevent this you can show it on coroutineScope as before.
Also, check out the more general solution implemented in the JetNews compose app example. I suggest you download the project and inspect it starting from location where the snackbar is displayed.
https://github.com/Kotlin-Android-Open-Source/Jetpack-Compose-MVI-Coroutines-Flow/blob/master/core-ui/src/main/java/com/hoc/flowmvi/core_ui/rememberFlowWithLifecycle.kt
#Suppress("ComposableNaming")
#Composable
fun <T> Flow<T>.collectInLaunchedEffectWithLifecycle(
vararg keys: Any?,
lifecycle: Lifecycle = LocalLifecycleOwner.current.lifecycle,
minActiveState: Lifecycle.State = Lifecycle.State.STARTED,
collector: suspend CoroutineScope.(T) -> Unit
) {
val flow = this
val currentCollector by rememberUpdatedState(collector)
LaunchedEffect(flow, lifecycle, minActiveState, *keys) {
withContext(Dispatchers.Main.immediate) {
lifecycle.repeatOnLifecycle(minActiveState) {
flow.collect { currentCollector(it) }
}
}
}
}
class ViewModel {
val singleEvent: Flow<E> = eventChannel.receiveAsFlow()
}
#Composable fun Demo() {
val snackbarHostState by rememberUpdatedState(LocalSnackbarHostState.current)
val scope = rememberCoroutineScope()
viewModel.singleEvent.collectInLaunchedEffectWithLifecycle { event ->
when (event) {
SingleEvent.Refresh.Success -> {
scope.launch {
snackbarHostState.showSnackbar("Refresh successfully")
}
}
is SingleEvent.Refresh.Failure -> {
scope.launch {
snackbarHostState.showSnackbar("Failed to refresh")
}
}
is SingleEvent.GetUsersError -> {
scope.launch {
snackbarHostState.showSnackbar("Failed to get users")
}
}
is SingleEvent.RemoveUser.Success -> {
scope.launch {
snackbarHostState.showSnackbar("Removed '${event.user.fullName}'")
}
}
is SingleEvent.RemoveUser.Failure -> {
scope.launch {
snackbarHostState.showSnackbar("Failed to remove '${event.user.fullName}'")
}
}
}
}
}
Here's a modified version of Soroush Lotfi answer making sure we also stop flow collection whenever the composable is not visible anymore: just replace the LaunchedEffect with a DisposableEffect
#Composable
inline fun <reified T> Flow<T>.observeWithLifecycle(
lifecycleOwner: LifecycleOwner = LocalLifecycleOwner.current,
minActiveState: Lifecycle.State = Lifecycle.State.STARTED,
noinline action: suspend (T) -> Unit
) {
DisposableEffect(Unit) {
val job = lifecycleOwner.lifecycleScope.launch {
flowWithLifecycle(lifecycleOwner.lifecycle, minActiveState).collect(action)
}
onDispose {
job.cancel()
}
}
}

ViewModel retrieves empty List but it should not be empty (mutableStateOf)

I need some data from a Viewmodel in my MainActivity to use it in another composable. So I've tried it with a mutableStateOf() to get it out of the viewModel after it fetched the data and updates the values.
private val locationList: MutableState<MutableList<LocationScaffold>> = mutableStateOf(mutableListOf())
composable(route = Screen.LocationDestinationListScreen.route) { navBackStackEntry ->
val factory = HiltViewModelFactory(LocalContext.current, navBackStackEntry)
val viewModel: LocationViewModel =
viewModel("LocationDestinationListViewModel", factory)
locationList.value = viewModel.locationList.value
Log.d("viewModel", "${viewModel.locationList.value}")
val lifecycleOwner = LocalLifecycleOwner.current
LocationDestinationListScreen(
viewModel = viewModel,
lifecycleOwner = lifecycleOwner,
navigation = { navController.navigate(it) })
}
composable(
route = Screen.BoxScreen.route + "/{locationId}",
arguments = listOf(navArgument("locationId") {
type = NavType.IntType
})
) { navBackStackEntry ->
val factory = HiltViewModelFactory(LocalContext.current, navBackStackEntry)
val viewModel: HistoryViewModel = viewModel("HistoryViewModel", factory)
val activeLocation: Int? = navBackStackEntry.arguments?.getInt("locationId")
activeLocation?.let {
BoxScreen(viewModel, locationList.value[it])
}
}
These are the navigation composables.
LocationDestinationListScreen starts a scan for BT Devices and fetches some data from a Server
also there is a LazyColumn which shows the result of the data fetching what means that viewmodel.locationList.value is definetly not empty and gets updated, but unfortunately not on the MainActivity side. Am I missing something here or what have I forgotten?
Because as far as I understand the Flow is:
Composable gets built
startScan in composable starts
on found the method calls locationList.value in the viewmodel which updates the data
the data runs through the composable and should update all data
I find this kinda weird because on other navigations it works fine like:
composable(route = Screen.LoginScreen.route) { navBackStackEntry ->
val factory = HiltViewModelFactory(LocalContext.current, navBackStackEntry)
val viewModel: LoginViewModel = viewModel("LoginScreenViewModel", factory)
when (viewModel.authenticationState.value) {
AuthenticationStateListener.Loading -> CenterLoadingIndicator()
AuthenticationStateListener.Authenticated -> {
navController.navigate(Screen.StartScanScreen.route)
if (user.value.name.isNullOrEmpty()) user.value = viewModel.user.value
}
AuthenticationStateListener.NotAuthenticated -> viewModel.openRequestDialog(
this#MainActivity,
"Something went wrong",
R.drawable.ic_baseline_error_24
) { _, _ -> }
}
LoginScreen(viewModel = viewModel)
}
This also listens to a MutableState and it gets correctly redirected after the state value gets changed.

Categories

Resources