/flow-test-observer

Kotlin Flow testing has never been easier

Primary LanguageKotlinMIT LicenseMIT

Kotlin Flow test observer

Build Status

Library inspired by TestSubscriber from RxJava. Works with both cold/finite and hot/infinite flow. Find in this Medium post some more information about the motivation of the library.

Getting started

Setting up the dependency

Step 1. Add the JitPack repository to your build file Add it in your root build.gradle at the end of repositories:

allprojects {
    repositories {
        ...
        maven { url 'https://jitpack.io' }
    }
}

Step 2. Add the dependency

testImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:$latest"
testImplementation "com.github.ologe:flow-test-observer:1.x.y"

(Please replace x and y with the latest version numbers:

Usage

@Test
fun `finite flow test`() = runTest(UnconfinedTestDispatcher()) {
    val flow = flowOf(1, 2, 3)   
      
    flow.test(this) {
        assertValues(1, 2, 3)
        assertValueCount(3)
        assertComplete()
    }   
}

// works as well with infinite flows 👍
@Test
fun `infinite flow test`() = runTest(UnconfinedTestDispatcher()) {
    val flow = channelFlow<Int> {
        offer(1)
        offer(2)
        
        awaitClose()
    }
    
    flow.test(this) {
        assertValues(1, 2)
        assertValueCount(2)
        assertNotComplete()
    }
}

All available assertions can be found here

Here are some simple examples on how to test different channel:

Bugs and Feedback

For bugs, questions and discussions please use the Github Issues.