Thursday, 27 August 2020

Testing RxJava repeatWhen with Mockk returnsMany

I'm trying to test multiple server responses with Mockk library. Something like I found in this answer for Mockito.

There is my sample UseCase code, which every few seconds repeats call to load the system from a remote server and when the remote system contains more users than local it stops running (onComplete is executed).

override fun execute(localSystem: System, delay: Long): Completable {
    return cloudRepository.getSystem(localSystem.id)
        .repeatWhen { repeatHandler -> // Repeat every [delay] seconds
            repeatHandler.delay(params.delay, TimeUnit.SECONDS)
        }
        .takeUntil { // Repeat until remote count of users is greater than local count
            return@takeUntil it.users.count() > localSystem.users.count()
        }
        .ignoreElements() // Ignore onNext() calls and wait for onComplete()/onError() call
    }

To test this behavior I'm mocking the cloudRepository.getSystem() method with the Mockk library:

@Test
fun testListeningEnds() {
    every { getSystem(TEST_SYSTEM_ID) } returnsMany listOf(
        Single.just(testSystemGetResponse), // return the same amount of users as local system has
        Single.just(testSystemGetResponse), // return the same amount of users as local system has
        Single.just( // return the greater amount of users as local system has
            testSystemGetResponse.copy(
                owners = listOf(
                    TEST_USER,
                    TEST_USER.copy(id = UUID.randomUUID().toString())
                )
            )
        )
    )

    useCase.execute(
        localSystem = TEST_SYSTEM,
        delay = 3L
    )
        .test()
        .await()
        .assertComplete()
}

As you can see I'm using the returnsMany Answer which should return a different value on every call.

The main problem is that returnsMany returns the same first value every time and .takeUntil {} never succeeds what means that onComplete() is never called for this Completable. How to make returnsMany return a different value on each call?



from Testing RxJava repeatWhen with Mockk returnsMany

No comments:

Post a Comment