https://kotlinlang.org logo
#mockk
Title
# mockk
m

Michael Pohl

09/29/2020, 7:28 AM
Is there somebody who can tell me how to mock/test a coroutine that takes a while to complete, like a network call? I have something like this in a test:
Copy code
coEvery { mockRepo.saveToServer(mockArgument) } returns myResult
Now this will of course happen immediately. In reality it could take a moment. Now while this call is in flight, I flip a boolean to prevent issuing a second call while the first one is still underway. When it returns, I flip the boolean back. Is there a proper way to unit test this, preferably using
Mockk
, of course...?
j

Joe

09/29/2020, 4:30 PM
Something along the lines of :
Copy code
coEvery {...} coAnswers { delay(100); myResult }
should work for simulating a delay, though you probably want to use some sort of synchronization mechanism (atomic booleans/ channel/ mutex/ semaphore/ etc) rather than a
delay
to coordinate between the test body and the mock.
m

Michael Pohl

09/29/2020, 6:16 PM
that's probably true. I have very limited experience with testing that kind of thing. I guess I'll have to do some Googling...
c

christophsturm

10/06/2020, 3:55 PM
you really should try to avoid sleeping in tests, or any kind of time dependency in tests. it makes tests very brittle
m

Michael Pohl

10/07/2020, 4:31 AM
Oh, I totally agree. I'm just unsure how to test this, but maybe I just have to change the structure of the functionality under testing here.
c

christophsturm

10/07/2020, 8:51 AM
can you share your current logic?
m

Michael Pohl

10/19/2020, 9:50 AM
sorry, this took a while. It's something like this: While a
Job
is running, it is stored in a variable, so that actions can first test if that variable isn't null and react to that (in this case by just returning if a second request is started). (it's happening in a Android viewModel by the way, but that should not be important here.)
3 Views