java unit test code_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:

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

-Cons: it would bring some complexity.

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

--Cons: Hard to cover timeout case.

回答1:

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).

回答2:

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值