Dan Johansson
05/29/2019, 3:54 PMasync
(and .await
in my test) it fails as expected but I want to use launch
(actual function is in my Android ViewModel) and I am kinda lost.
A workaround is to check whether the job isCancelled
, which works but is a bit clunky (I guess it's possible to create some test rule..). I've read the docs but haven't come up with anything. Maybe I'm going about this the wrong way and there's a better approach? Any pointer or direction is very much appreciated.
// in ViewModel
val job = Job()
val viewModelScope = CoroutineScope(Dispatchers.Main + job)
fun someFunction() = viewModelScope.launch {
throw IllegalStateException("reasons")
}
...
@Test
fun `should fail`() = runBlocking {
// prints error but the test passes
someFunction().join()
}
@Test
fun `successfully failing workaround`() = runBlocking {
// this feels wrong
val job = someFunction()
someFunction.join()
assertFalse(job.isCancelled)
}
gildor
05/29/2019, 4:59 PMDan Johansson
05/29/2019, 5:02 PMDispatchers.Main
.Dan Johansson
05/29/2019, 6:10 PMviewModelScope
with the CoroutineScope
from the test it behaves as one would expect.
I'll have to check if I can put my test specific Dispatcher
there and have it blow up in a more structured way for my next session..gildor
05/29/2019, 11:19 PMDan Johansson
05/30/2019, 3:27 AMprivate val mainThreadSurrogate = newSingleThreadContext("UI thread")
@Before
fun setUp() {
Dispatchers.setMain(mainThreadSurrogate)
}
@After
fun tearDown() {
Dispatchers.resetMain() // reset main dispatcher to the original Main dispatcher
mainThreadSurrogate.close()
}
gildor
05/30/2019, 5:32 AMgildor
05/30/2019, 5:32 AMmainThreadSurrogate
with Dispatchers.Unconfined to run it on the same thread where it invokedgildor
05/30/2019, 5:33 AMDan Johansson
05/30/2019, 5:51 AMDispatchers.Unconfined
in place of mainThreadSurrogate
as you mention.Dan Johansson
05/30/2019, 6:15 AMgildor
05/30/2019, 6:37 AMDan Johansson
05/30/2019, 6:44 AMDan Johansson
05/30/2019, 6:47 AMThread.setDefaultUncaughtExceptionHandler
for testing purposes? I managed to create a rule that fails the test by collecting Exceptions and then after the test is finished verifying that no exceptions was found.gildor
05/30/2019, 6:50 AMDan Johansson
05/30/2019, 6:52 AMDan Johansson
05/30/2019, 6:52 AMgildor
05/30/2019, 6:55 AMDan Johansson
05/30/2019, 7:04 AMbefore join main @coroutine#1
in launch main @coroutine#2
Exception in thread "main @coroutine#2" java.lang.IllegalStateException
.... (removed the rest of the trace)
after join main @coroutine#1
Dan Johansson
05/30/2019, 7:05 AMDispatchers.setMain(Dispatchers.Unconfined)
gildor
05/30/2019, 7:11 AMgildor
05/30/2019, 7:12 AMgildor
05/30/2019, 7:12 AMDan Johansson
05/30/2019, 7:14 AMThread.currentThread().name
Dan Johansson
05/30/2019, 7:15 AMgildor
05/30/2019, 7:15 AM