简体   繁体   中英

RxJava Unit test Observable interval, Change response by advancing through time

I have a network polling function with Observable interval in my repository

class repository @Inject constructor(
    private val api: api,
    private val schedulerProvider: SchedulerProvider
) {

    private fun networkPoll(): Observable<response> {
        return Observable.interval(1L, TimeUnit.Seconds, schedulerProvider.io())
            .startWith(0L)
            .flatMap {
                api.getStatus().subscribeOn(schedulerProvider.io()).toObservable()
            }
    }

    private fun pollStates(): Observable<State> {
        return networkPoll()
            .map {
                // map the response to State1, State2, State3
            }
    }

    fun pollForState3(): Observable<State> {
        return pollStates()
            .subscribeOn(schedulerProvider.io())
            .takeUntil {
                it is State3
            }
    }

}

How do I unit test pollForState3 and change the response by advancing through time?

I solved it by doing this

private lateinit var repository: Repository
private val schedulerProvider = TestSchedulerProvider()

@Mock
private lateinit var api: Api

    @Before
    fun setup() {
        repository = repository(api, schedulerProvider)
    }

@Test
fun test() {
    `when`(api.getStatus()).thenReturn(
        // return such a way that pollStates function map this to State1
    )
    val testObserver = repository.pollForState3().test()
    schedulerProvider.ioScheduler.advanceTimeBy(1L, TimeUnit.MILLISECONDS)
    testObserver.assertValue {
        it is State1
    }
    testObserver.assertNotTerminated()

    `when`(api.getStatus()).thenReturn(
        // now return such a way that pollStates function map this to State3
    )
    schedulerProvider.ioScheduler.advanceTimeBy(2L, TimeUnit.SECONDS)
    testObserver.assertValue {
        it is State3
    }
    testObserver.assertTerminated()
    testObserver.dispose()
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM