:android-wave: Hey folks Did anyone tried testing...
# flow
p
đź‘‹ Hey folks Did anyone tried testing the
catch
operator? This test case fails with a crash. Whereas if i don't use
catch
operator but used
try-catch
the test is as expected
Just incase anyone wants to take a look. https://github.com/prudhvir3ddy/flows-practice
f
you are throwing an exception on the access to the flow, not during the flow's emissions. if you want to test an exception during the flow collection, do something along the lines of
Copy code
override fun invoke(): Flow<int> = flow {
    throw Exception()
}
e
^^ at the point you're throwing the exception, the flow doesn't even exist yet, nevermind being able to catch it terminating with an exception…
p
Thanks for answering folks. If i'm correct This code better be wrapped in a try catch So we can catch all kinds of exceptions which can be throwed at test() Including creating the flow
f
you shouldn't use try/catch in tests, if there are exceptions in tests you want them to fail, unless you're explicitly testing for an exception (which you wouldn't do with a try/catch)
p
I mean to cover the main code with
try catch
instead of using
catch
operator
Copy code
fun test() {
    try {
        mainUseCase.invoke()
            .flowOn(dispatcher.default())
            .onEach {
                //No op
            }
            .launchIn(viewModelScope)
    } catch (e: Exception) {
        isError = true
    }
}
Yeah i'm testing if an exception occurs and gets handled as expected
f
don't add the try/catch; if the exception is not handled the test will fail
e
I wouldn't say so. with the exception of some hot flows, work should be done inside the flow only when subscribed. then there is no reason the flow creator should throw.
âś… 1
p
I see, thanks.