Skip to content

Async Testing ‐ Why testing async code blocks is hard

Devrath edited this page Oct 25, 2023 · 2 revisions

github-header-image (1)

Async code

  • Testing async code is always a challenge in any application.
  • In Android all the new apps use suspend functions.

There are challenges in testing the async code

  • It is very hard to predict the order in which async code blocks are executed.
  • Since the tests are executed synchronously, and all the async code runs parallel, this might cause the test to break.
  • So as we know tests are set linearly like setup then execute then finally assert. There can be a possibility that we might end up asserting values even though the execution phase is not completed which might end up failing tests.
  • Async code might lead to race-conditions of functions being the tests failing sometimes and succeeding sometimes leading to flaky tests.

Approaches to solve the challenge

  • So since async behavior is the cause of tests failing, we should make our code async to synchronous.
  • This will enable tests to run on a single thread so we can assert values as we know what happens next.
  • We can just replace the normal dispatcher of the coroutines with a test dispatcher so that we can make it synchronous.