Skip to content

Instantly share code, notes, and snippets.

@Nunocky
Last active June 25, 2023 01:41
Show Gist options
  • Save Nunocky/d43aa872ca6193a9210a625f32a06111 to your computer and use it in GitHub Desktop.
Save Nunocky/d43aa872ca6193a9210a625f32a06111 to your computer and use it in GitHub Desktop.
ViewModelで実行されるコルーチンのテスト。 UIStateの変化を見る
package com.example.myapplication
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import kotlin.random.Random
class ExampleUseCase {
suspend fun getValue(): Int {
delay(1500)
return Random.nextInt(0, 100)
}
}
class ExampleViewModel(savedStateHandle: SavedStateHandle, private val useCase: ExampleUseCase) :
ViewModel() {
private val _uiState = MutableStateFlow(UIState.INIT)
val uiState = _uiState.asStateFlow()
private val _value1 = SavableMutableSaveStateFlow(savedStateHandle, "value1", 0)
val value1 = _value1.asStateFlow()
enum class UIState {
INIT,
LOADING,
SUCCESS
}
fun process() {
viewModelScope.launch(Dispatchers.IO) {
_uiState.value = UIState.LOADING
_value1.value = useCase.getValue()
_uiState.value = UIState.SUCCESS
}
}
}
package com.example.myapplication
import com.example.myapplication.ExampleViewModel.UIState
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.lifecycle.SavedStateHandle
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.test.setMain
import org.junit.After
import org.junit.Assert.*
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@ExperimentalCoroutinesApi
@RunWith(JUnit4::class)
class ExampleViewModelTest {
@get:Rule
val instantTaskExecutorRule = InstantTaskExecutorRule()
@Before
fun setUp() {
Dispatchers.setMain(Dispatchers.Unconfined)
}
@After
fun tearDown() {
Dispatchers.resetMain()
}
@Test
fun test1() = runTest {
val savedStateHandle = SavedStateHandle()
val useCase = ExampleUseCase()
val viewModel = ExampleViewModel(savedStateHandle, useCase)
viewModel.process()
assertEquals(UIState.LOADING, viewModel.uiState.first())
while (viewModel.uiState.first() != UIState.SUCCESS) {
delay(100)
}
assertEquals(UIState.SUCCESS, viewModel.uiState.first())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment