Skip to content

Instantly share code, notes, and snippets.

@Ghedeon
Created February 1, 2019 18:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ghedeon/e87ed9d287071105ca427b5e9fa05305 to your computer and use it in GitHub Desktop.
Save Ghedeon/e87ed9d287071105ca427b5e9fa05305 to your computer and use it in GitHub Desktop.
Coroutine Test
class AccountOwnerTypeViewModelTest {
@Rule
@JvmField
val rule = InstantTaskExecutorRule()
val mainThreadSurrogate = newSingleThreadContext("UI thread")
@Before
fun setUp() {
Dispatchers.setMain(mainThreadSurrogate)
}
@After
fun tearDown() {
Dispatchers.resetMain()
mainThreadSurrogate.close()
}
@Test
fun bar(){
val viewModel = ViewModel()
val acc = mutableListOf<Int>()
viewModel.foo.observeForever{acc.add(it)}
runBlocking {
repeat(100) {
viewModel.start()
}
}
assertEquals(acc, IntArray(100){it}.asList())
}
class ViewModel : CoroutineScope {
private val job = Job()
override val coroutineContext: CoroutineContext = job + Dispatchers.Main
val foo = MutableLiveData<Int>()
private var i = 0
fun start(){
launch{
foo.postValue(i++)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment