https://kotlinlang.org logo
#rx
Title
# rx
a

Ariana

12/27/2019, 5:31 PM
Hey all, I’m trying to unit test using Robolectric and am running into a weird scenario Here’s the code block I’m executing:
Copy code
Maybe.just(list)
    .flatMapSingle { repository.getStuffList(id) }
    .map { stuffList -> stuffList.filter { stuff -> list.contains(stuff) } }
    .flatMapCompletable { stuffAfterFilter ->
         secondRepository.doThing(stuffAfterFilter)
              .doOnError { Completable.error(IllegalStateException("failure")) }
              .andThen { repository.deleteStuff(stuffAfterFilter) }
     }
     .andThen(repository.getStuffList(id))
What’s the best way to have each call to
repository.getStuffList(id)
return different items when they’re called? Right now I’ve got order of operations setup in my test (which has worked in the past), but now the first time the method is called it’s returning
stuffList2
instead of
stuffList1
Copy code
whenever(repository.getStuffList("id")).thenReturn(Single.just(stuffList1))
whenever(secondRepository.doThing(any())).thenReturn(Completable.complete())
whenever(repository.deleteStuff(any())).thenReturn(Completable.complete())
whenever(repository.getStuffList("id")).thenReturn(Single.just(stuffList2))
Am I on the right path here?
p

Paul Woitaschek

12/28/2019, 9:53 AM
Use fromCallable and handle your logic there. You should treat rx as encapsulated function and don't rely on subscription happening immediately
a

Ariana

12/30/2019, 4:27 PM
Ah, I’ve never heard of that before. You’re saying use
fromCallable
in the test?
p

Paul Woitaschek

12/30/2019, 4:30 PM
Yes that way you can keep track of the subscriptions
Copy code
val stuffList1 = listOf(1,2,3)
    val stuffList2 = listOf(4,5,6)
    var invocation = 0
    Single.fromCallable {
        when(++invocation){
            1 -> stuffList1
            2 -> stuffList2
            else -> error("Didn't answer invocation $invocation")
        }
    }
a

Ariana

12/30/2019, 4:31 PM
Oh that’s amazing. Thank you!
2 Views