Is there somebody who can tell me how to mock/test...
# mockk
m
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
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
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
you really should try to avoid sleeping in tests, or any kind of time dependency in tests. it makes tests very brittle
m
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
can you share your current logic?
m
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.)