weijia_yu
weijia_yu

Reputation: 1015

Is it a good practice to unit test asynchronous code?

It is definitely possible to test asynchronous code by letting the thread wait until the asynchronous code finishes. However, is it encouraged to test asynchronous code. Or instead, should we seperate the logic and only test the synchronous part?

For example, in my app I would make a REST API call to fetch json from server and then I need to parse the json.

There are two approaches:

  1. Test the fetching and parsing as a whole. We can use MockWebServer to simulate timeout and response.

    -Cons: it would bring some complexity.

  2. Just test the parsing part, since we cannot control the API call part; it is controlled by okhttp

    --Cons: Hard to cover timeout case.

Upvotes: 2

Views: 516

Answers (2)

hunter
hunter

Reputation: 4173

since your question specially ask about "Unit tests", the simple answer is "No". unless the unit you test is not interested of the result of Async call, it is not a part of your unit.unit tests should only make sure your unit works properly. in this case you should verify Async call is dispatched properly (so it will be a white box test).

Upvotes: 1

Alexei Kaigorodov
Alexei Kaigorodov

Reputation: 13535

Test are organized in hierarchy. The lowest level tests logic, the next level tests how the logic is called within framework (in your case, asynchronous http), and finally, manual tests with browser (if you are making a website). All levels must be tested. Often all program units work well but the application does not.

Upvotes: 0

Related Questions