Is there something similar to RxJava `TestObserver...
# coroutines
t
Is there something similar to RxJava
TestObserver
to test coroutines
Flow
?
m
I can't find anything on flow testing on that page
so basically answer is no?
g
What exactly about flow testing do you need?
For example things related to delay are there
there is no
assert()
extensions for example, but do you really need one? maybe you need some particular feature of TestObserver
t
Since I'm dealing with infinite `Flow`s, I'd like to collect items one by one (the Rx equivalent would be
awaitCount(Int)
) and perform assertions on them. What are your recommendations for testing simpler flows ? Collect as
List
with
toList
and perform assertions on the list ?
s
Would be a great addition to the kotlinx-coroutines-test library:
fun <T> Flow<T>.test(): TestCollector<T>
and a new class
TestCollector<T>
. I'd open a PR or issue to add this to the library. (It would function like an Rx TestObserver/TestSubscriber)
p
Well I didnt find the rx test too helpful. What actually happening is the testobserver duplicating what assertion libraries already do
I'd do the flow logic assertions using assert libraries:
Copy code
runBlockingTest{
       val firstThreeItems = withTimeout(1000) {
         flowOf(1, 2, 3, 4).take(3).toList()
       }
        assertThat(firstThreeItems)...
      }
1
j
SQL Delight has some infrastructure for this: https://github.com/cashapp/sqldelight/blob/master/extensions/coroutines-extensions/src/commonTest/kotlin/com/squareup/sqldelight/runtime/coroutines/FlowAssert.kt Looks like:
Copy code
@Test fun queryNotNotifiedAfterCancel() = runTest {
    db.createQuery(TABLE_EMPLOYEE, SELECT_EMPLOYEES, MAPPER)
        .asFlow()
        .test {
          expectItem().assert {
            hasRow("alice", "Alice Allison")
            hasRow("bob", "Bob Bobberson")
            hasRow("eve", "Eve Evenson")
          }

          cancel()

          db.employee(Employee("john", "John Johnson"))
          expectNoMoreEvents()
        }
  }
👍 2
s
@Paul Woitaschek If the
flow
under test doesn’t complete, a terminating function on it never resumes. There is where something like a TestCollector or @jw’s example can help out.
v
It would be very nice if you could create an issue with a desired API shape and a bit of context (e.g. which particular problem this API helps to solve)
👍 1
m
It's great to see https://github.com/cashapp/turbine just released. 👏
👍 1
p
Already using that. Please incorporate that in the coroutines testing artifact 🙏