Hi Kotlin Community, So i working on project and i want to ask how to test your concurrency code in unit test , so i know my code working fine ?
Unit tests should be small and deterministic it doesn’t sound like you want a unit test.
If you are wondering about unit testing with coroutines in general then you have a couple options
- If you just have simple non-delaying suspend methods, runBlocking is all you need.
- If you are testing code that launches coroutines or delays, then you’ll want to look at runBlockingTest here: kotlinx.coroutines/kotlinx-coroutines-test at master · Kotlin/kotlinx.coroutines · GitHub. It lets you control the clock and fails for you if coroutines are leaking past the test.
Also keep in mind that coroutines are not necessarily concurrent. Many coroutines can run on the same thread. Depending on the project, there may be no need to use anything besides the Main dispatcher in which case there’s no actual concurrency at all.
If your unit do something with other units by cuncurrent way - you just need to mock all outer units wich operable by this unit and test all cases of this unit behaviour. Just like you testing non-cuncurrent units. For eample if you testing some reactive flow - you can test it with random Int emitter or mock emitter classes with test()… and also don’t forget for emitting error cases.