Saturday, May 12, 2012

TDD - Testing AsyncTasks on Android

Testing functionalities of a software system is probably one of the most important things to do if you want to release a reliable application to your clients.

TDD (aka Test Driven Development) is a methodology where you create and develop unit tests before writing a single line of application logic. This strategy allows you to better understand the problem your app is solving, it gives you a more pragmatic and structured way to build a software component. It forces you to design and think to the solution in detail before coding it. And, most important, when you change something in your code, you can safely run your tests again and have an immediate result if your changes have affected the behavior of the component.

I usually do TDD to test model classes, database classes and networking. I'm not writing functional tests on the UI but Android offers you tools like monkey to test also user clicks on your UI.

If your code use AysncTasks to perform networking operations in a background thread, things become a little trickier.

Normally, in a AysncTask, you can specify a result of this task using onPostExecute.
This call is executed on the main thread so you can update your UI and notify the user easily.

AsyncTask runs your task in a background thread, but this opens some issues: our tests must be run on the main thread! We need to wait for the AsyncTask to finish before jumping to the next test or to quit the testing routine.
There is a method called runTestOnUiThread that perform a testcase on a main thread. To use such method, your class must extend InstrumentationTestCase.





In the previous code snippet, I'm creating a unit test called testGetMedia whose purpose is doing some networking in an asynchronous fashion, to fetch some data from a remote backend.
The tested class is called NetworkTasks and it contains a method called getMedia(Media) similar to this one:



GetAsyncMediaTask is a subclass of AsyncTask that implements the doInBackground() and the onPostExecute() methods. I'm not showing the code of GetAsyncMediaTask here because is not really interesting for our purpose. In the doInBackground() method an http call is placed and it blocks the calling thread until it gets an HttpResponse; inside the onPostExecute() method, I'm using the listener passed to the NetworkTasks object to notify the component that has launched it. The component is notified through onFail and onSuccess callbacks.
In the code snippet the listener is called GetMediaListener.
This covers almost everything except for few (important!) details: what happens in the GetMediaListener?




The GetMediaListener extends a generic CallbackListener which in turn implements a simple interface with two methods (onFail and onSuccess).
The callbacks are here used to assert that a condition holds or doesn't hold. The listener used in the real code will do some useful stuff on the UI, trigger some notifications and so on.
And here comes into play the CountDownLatch object. It is absolutely mandatory to use this object when you want to test an AsyncTask. Infact, even if we're running the task on the main thread, as soon as the doInBackground method ends, the testGetMedia() method ends too, and there is no way for the listener to be invoked by the system! By using a CountDownLatch, we impose the current thread to stop and wait until a certain condition is met: here we wait that the callback onPostExecute (which in turns call onFail or onSuccess) is executed: as soon as it is executed, the object is decremented with the countdown() method of the supreclass and the lock is removed. The lock is automatically removed after 30 seconds by the signal.await() call.

You can get all the code here: https://gist.github.com/2667108

Enjoy async TDD on Android! :)

131 comments:

  1. Excellent post, thanks for collating the information. I have been searching google and yahoo for information related to this and it led me to your blog! :-)
    Magento Development Company | web design and development company

    ReplyDelete
  2. I think I've found a nice informative blog after searching a long time. Thanks for your great articles and information, Its very Helpful for everyone.The contents are quiet interesting. I will be waiting for your next post.
    android app development perth | android app development sydney

    ReplyDelete
  3. Hi,

    Thanks for sharing a very interesting article about TDD - Testing AsyncTasks on Android. This is very useful information for online blog review readers. Keep it up such a nice posting like this.

    From,
    Maestro Infotech,
    Web Design Company Bangalore

    ReplyDelete
  4. this is one of the best information i have ever seen.. thanks for sharing this.
    Website developemnt comapany in bangalore

    ReplyDelete
  5. Hi,

    Thanks for sharing a very interesting article about testing async android. This is very useful information for online blog review readers.

    From,
    WondersMind,
    Web Design Company in Bangalore

    ReplyDelete
  6. This is great information. Testing Async tasks in mobile app development is very important. If not checked properly, it can slow down the app. You have really explained it well..

    We are an Web design and Development company in Banagalore providing mobile application development company developing Android and IOS apps. Anyone looking for such services can contact Site Galleria

    ReplyDelete
  7. Thank for sharing an excellent post.

    https://www.creatorswebindia.com/

    Web Design in chennai

    Web design Company in chennai

    Website Design in chennai

    Website Design Company in chennai

    website company in chennai

    Web development in chennai

    Web development Company in chennai

    Web Designer in chennai

    Web Designer Company in chennai

    website designer in chennai

    website designer company in chennai

    ReplyDelete
  8. I read your post and it was so nice and I was thinking that how good you are doing just to make your readers happy. Well, Continue this effort so that we always look for more. Gate Automation Pakistan

    ReplyDelete
  9. Hi,

    Thanks for sharing a very interesting article about TDD - Testing AsyncTasks on Android. This is very useful information for online blog review readers. Keep it up such a great article like this.

    Regards,
    WondersMind,
    Web Design Company Bangalore

    ReplyDelete
  10. mobileengineering! could your please share source code with me, i need to mix two audio files. i shall be very thankful to you/
    EMAIL: rashidhameed310@gmail.com

    ReplyDelete
  11. Excellent Article. Well, the main reason of me sharing my post here is that, Lets Connect over the Digital Marketing Company in India and we also open for Partnerships with Mobile App Development, Website Development and Graphics related company !

    Get in touch with the Digital Marketing Service Provider In India for more information

    ReplyDelete
  12. Hey I loved the way you shared the valuable information with the community. I would say that please continue these efforts and we want to hear more from you.
    SEO Expert In Pakistan

    ReplyDelete
  13. Good work…unique site and interesting too… keep it up…looking forward for more updates.Good luck to all of you and thanks so much for your hard-work.Seo Expert in Pakistan

    ReplyDelete
  14. I read your post and it was so nice and I was thinking that how good you are doing just to make your readers happy.
    Umer Anees

    ReplyDelete
  15. Articles and content in this section of the website are really amazing. Great ideas indeed! I will surely keep these in my mind!
    SEO Services in Pakistan

    ReplyDelete
  16. Online store Brumer.com offers the wide range of high-quality Laboratory glassware. All you have to do is to make choice and to place order on our website. We will contact you right away in order to specify every single detail of your purchase and delivery. No matter where you live – our company will gladly deliver your order worldwide.

    ReplyDelete
  17. It’s been great to land on your blog as I got many interesting information from this. Thanks for giving this code. This code will help many android developers who are going to testing async tasks.

    ReplyDelete
  18. I recently found many useful information in your website especially this blog page. Among the lots of comments on your articles. Thanks for sharing.
    royaltyfree backing tracks

    write a song now

    ReplyDelete
  19. Hello thanks for sharing your valuable information
    The post is really good, we will use above mentioned strategy in our website development company in Bangalore.

    ReplyDelete
  20. This is great information. Testing Async tasks in mobile app development is very important. TORC WEB DESIGN

    ReplyDelete
  21. Thanks Infonya, admin.

    Untuk mencari referensi website pertanian, peternakan dan perikanan saya sarankan untuk mengunjungi website ini ya min.Soalnnya sangat lengkap dan mudah dipahami.


    Ilmu Pengetahuan

    Ilmu Peternakan

    ReplyDelete
  22. This comment has been removed by the author.

    ReplyDelete
  23. "I loved the post, keep posting interesting posts. I will be a regular reader...

    http://alliedmaterials.com.pk

    ReplyDelete
  24. "I loved the post, keep posting interesting posts. I will be a regular reader...

    http://www.alfalahhost.com/

    ReplyDelete
  25. This comment has been removed by the author.

    ReplyDelete
  26. I loved the post, keep posting interesting posts. I will be a regular reader...

    seo expert in pakistan

    ReplyDelete
  27. Really it is great topic and Very important Information for us, I have think the representation of this Information is actually great one. . Manage Your Google Shopping Ads

    ReplyDelete
  28. This comment has been removed by the author.

    ReplyDelete
  29. This comment has been removed by the author.

    ReplyDelete
  30. This blog is useful as well as informative. Keep sharing such blogs I really like your posts Generators UK

    ReplyDelete
  31. Very nice article, very informative and provides alot of insight of the project. new metro city

    ReplyDelete
  32. This blog is useful as well as informative. Keep sharing such blogs I really like your posts Kcal coupon code

    ReplyDelete
  33. This blog is useful as well as informative. Thanks for Sharing. new metro city

    ReplyDelete
  34. This blog is useful as well as informative. Keep sharing such blogs I really like your posts Bluetooth Earphones

    ReplyDelete
  35. This comment has been removed by the author.

    ReplyDelete
  36. Appreciating the hard work you put into your site and detailed information you offer. It’s nice to come across a blog every once in a while that isn’t the same out of date rehashed materialAffiliate marketing agency

    ReplyDelete
  37. I really appreciate your efforts and hope so that you will keep posting such contents for us.
    Packaged Gas compressors Pakistan

    ReplyDelete
  38. Appreciating the hard work you put into your site and detailed information you offer. It’s nice to come across a blog every once in a while that isn’t the same out of date rehashed material. Privacy netting

    ReplyDelete
  39. https://rent-a-car-islamabad.pk/



    At Rent-a-car-Islamabad.pk you will get 100% guaranteed lowest rates. We are operating in twin cities Rawalpindi & Islamabad. We have offices in Islamabad G-8, G-9, F-10 and Blue area. You can pick and drop vehicle from any of our offices. Now Rent a car in Islamabad is no hassle. Call us and book your car now from 247 car rental.



    info@rent-a-car-islamabab.pk

    ReplyDelete
  40. I have recently started a blog, the info you provide on this site has helped me greatly in blogging. Thanks for all of your work and timeBest law firm in Lahore

    ReplyDelete
  41. Very Informative topic I liked it very much. You have covered the topic in detail thumbs up Roofing Services Bronx

    ReplyDelete
  42. Very Informative topic I liked it very much. You have covered the topic in detail thumbs up Roof Repair Bronx

    ReplyDelete
  43. cumins generator in pakistan

    http://hnl.com.pk/

    If you are looking for cumins generator in pakistan, then you are at right place. HNL is one of the leading MS vendors in the country, working with all major telecom operators in Pakistan, maintaining around 12000 BTS and 20 Core sites.
    info@hnl.com.pk

    ReplyDelete
  44. Aw, this was a very nice post. Taking the time and actual effort to generate a very good article… but what can I say… I put things off a lot and never manage to get nearly anything done.
    Cloud tech

    ReplyDelete
  45. This comment has been removed by the author.

    ReplyDelete
  46. This truly is some great work.Appreciate it.We are a Seo Firm Bangalore.We offer services like SEO,PPC,SMM,online reputation management & web development both to small and medium companies.As a running offer,we are providing free performance audit for our customers

    ReplyDelete
  47. Web Design Companies in Bangalore
    Web Design Company in Bangalore
    Website Design Companies in Bangalore
    Web Development Company in Bangalore
    Website Development Company in Bangalore
    Website Designing Company in Bangalore
    Web Designing Company in Bangalore
    SEO Company in Bangalore

    #seocompanyinbangalore #seoagencyinbangalore #seoexpertsinbangalore #seodevelopment #seofriendly #searchengine #searchengineoptimization #seo #search #google #seodevelopment #seoteam #ranking #googlerank #webpage #googleranking #serp #searchresults #position

    ReplyDelete
  48. Web Design Companies in Bangalore
    Web Design Company in Bangalore
    Website Design Companies in Bangalore
    Web Development Company in Bangalore
    Website Development Company in Bangalore
    Website Designing Company in Bangalore
    Web Designing Company in Bangalore
    SEO Company in Bangalore

    #seocompanyinbangalore #seoagencyinbangalore #seoexpertsinbangalore #seodevelopment #seofriendly #searchengine #searchengineoptimization #seo #search #google #seodevelopment #seoteam #ranking #googlerank #webpage #googleranking #serp #searchresults #position

    ReplyDelete
  49. Such a nice blog post. I likes your post. Few days back i bought 100k active followers for instagram, and i would also suggest best website to Buy instagram followers India

    ReplyDelete
  50. thanks for posting wonder article blog.great Information blog, your article has very nice information.We at Fuel digital marketing give you the best eCommerce website development services in Chennai which will give you and your customers a one-stop solution and best-in-class services. We take your ideas and convert it into something simple and professional and that is what makes us one of the top-rated e-commerce development company in Chennai. We help you in gaining new marketing strategies, increase the range of your products which will, in turn, lead to the generation of more sales

    e commerce website development services in chennai | best woocommerce development company | best ecommerce website design company in coimbatore |ecommerce website designing company in chennai and coimbatore | opencart development company in coimbatore | opencart development company in chennai | woocommerce development company in chennai | woocommerce website designing company in chennai

    ReplyDelete
  51. https://maytinhdeban.hatenablog.com/entry/2020/08/10/155245
    https://www.ohay.tv/view/nhung-dau-hieu-may-tinh-de-ban-bi-nhiem-virus/Yb6ZKPvEkn
    https://medium.com/p/8e94adcd659d/edit?source=your_stories_page---------------------------
    https://maytinhdeban.livejournal.com/3078.html

    ReplyDelete
  52. https://www.ohay.tv/view/mua-may-tinh-ban-nhung-dieu-can-luu-y/jOYDuTnvQL
    https://maytinhdeban.hatenablog.com/entry/2020/09/01/171155?_ga=2.92378328.471105878.1598947922-517807338.1598947922
    https://medium.com/p/e759807b81c4/edit

    ReplyDelete
  53. Really Very helpful Post & thanks for sharing & keep up the good work. Fashion bloggers in India

    ReplyDelete
  54. http://www.catloc.vn/threads/115458-cach-tim-dia-chi-lap-dat-cua-luoi-chong-muoi-dang-xep-online.html#post148779
    http://penetron.vn/threads/157641-tim-dia-chi-lap-dat-cua-luoi-chong-muoi-theo-hinh-thuc-online-nhu-the-nao.html#post159040
    http://raonhanh.com.vn/threads/178291-meo-tim-dia-chi-lap-dat-cua-luoi-chong-muoi-dang-xep-theo-hinh-thuc-online.html#post180436
    http://phimbomtan.edu.vn/threads/95990-Tuyet-chieu-tim-dia-chi-ban-cua-luoi-chong-muoi.html#post118677
    http://www.catloc.vn/threads/115458-cach-tim-dia-chi-lap-dat-cua-luoi-chong-muoi-dang-xep-online.html#post148779

    ReplyDelete
  55. http://www.catloc.vn/threads/115458-cach-tim-dia-chi-lap-dat-cua-luoi-chong-muoi-dang-xep-online.html#post148779
    http://penetron.vn/threads/157641-tim-dia-chi-lap-dat-cua-luoi-chong-muoi-theo-hinh-thuc-online-nhu-the-nao.html#post159040
    http://raonhanh.com.vn/threads/178291-meo-tim-dia-chi-lap-dat-cua-luoi-chong-muoi-dang-xep-theo-hinh-thuc-online.html#post180436
    http://phimbomtan.edu.vn/threads/95990-Tuyet-chieu-tim-dia-chi-ban-cua-luoi-chong-muoi.html#post118677
    http://www.catloc.vn/threads/115458-cach-tim-dia-chi-lap-dat-cua-luoi-chong-muoi-dang-xep-online.html#post148779

    ReplyDelete
  56. https://www.ohay.tv/view/tu-van-cau-hinh-may-tinh-de-ban-danh-cho-dan-van-phong-lam-ke-toan/gD3ROCGW6a
    https://maytinhdeban.hatenablog.com/entry/2020/09/28/191314
    https://medium.com/p/adb2a963a6b3/edit

    ReplyDelete
  57. https://meochongmuoi.blogspot.com/2020/10/7-cach-xua-uoi-muoi-ra-khoi-nha.html
    https://bancuachongmuoiuytinhathanhcaocap.blogspot.com/2020/10/meo-hay-uoi-muoi-ra-khoi-nha.html
    https://cualuoichongmuoihoangminhgiare.blogspot.com/2020/10/meo-hay-chong-muoi-voi-vai-meo-on-gian.html
    https://tonghopmeovatcuocsong247.blogspot.com/2020/10/meo-hay-chong-muoi-on-gian-tai-nha.html

    ReplyDelete
  58. https://meochongmuoi.blogspot.com/2020/10/7-cach-xua-uoi-muoi-ra-khoi-nha.html
    https://bancuachongmuoiuytinhathanhcaocap.blogspot.com/2020/10/meo-hay-uoi-muoi-ra-khoi-nha.html
    https://cualuoichongmuoihoangminhgiare.blogspot.com/2020/10/meo-hay-chong-muoi-voi-vai-meo-on-gian.html
    https://tonghopmeovatcuocsong247.blogspot.com/2020/10/meo-hay-chong-muoi-on-gian-tai-nha.htm

    ReplyDelete
  59. software testing company in India
    software testing company in Hyderabad
    very useful and informative article.
    Thanks for sharing such a valuable information with us.
    keep sharing.

    ReplyDelete
  60. Atlast I found a Great post on mobile web app development, after searching many resource's, and I think its the best of all articles on mobile web app development, it will be very helpful for everyone. The contents are upto the best standard, I will be waiting for more great posts like this.

    ReplyDelete

  61. Chennai IT Training Center
    Artificial Intelligence training in chennai - Basically AI Artificial Intelligence is a programming which is created for robots to think and work on there own without the help of humans.

    RPA Training Institute in Chennai - RPA is useful in making complex decision by collaborating with Artificial Intelligence. And it will also contribute to the market of Big data and IOT. Join the Best RPA Training Institute in Chennai now.

    Load runner training in Chennai - Load runner is an software testin tool. It is basically used to test application measuring system behaviour and performance under load. Here comes an Opportunity to learn Load Runner under the guidance of Best Load Runner Training Institute in Chennai.

    apache Spark training in Chennai - Apache Spark is an open- source, Split Processing System commonly used for big data workloads. Learn this wonderful technology from and under the guidance of Best Apache spark Training Institute in Chennai.

    mongodb training in chennai - MongoDB is a cross platform document - oriented database Program. It is also classified as NO sql database Program. Join the Best Mongo DB Training Institute in Chennai now.

    ReplyDelete
  62. SEO Ireland is one of the pioneer in introducing mobile web app development in Ireland, in the year 2006 one few people know about mobile aps, Cliqued Media was developing mobile aps for its customers

    ReplyDelete
  63. Ireland web design is making mobile aps for its customers since 2006, Cliqued Media has developed its custom codes for mobile web apps that are helping millions of new coders

    ReplyDelete
  64. This post is really amazing
    Village Talkies a top-quality professional corporate video production company in Bangalore and also best explainer video company in Bangalore & animation video makers in Bangalore, Chennai, India & Maryland, Baltimore, USA provides Corporate & Brand films, Promotional, Marketing videos & Training videos, Product demo videos, Employee videos, Product video explainers, eLearning videos, 2d Animation, 3d Animation, Motion Graphics, Whiteboard Explainer videos Client Testimonial Videos, Video Presentation and more for all start-ups, industries, and corporate companies. From scripting to corporate video production services, explainer & 3d, 2d animation video production , our solutions are customized to your budget, timeline, and to meet the company goals and objectives.
    As a best video production company in Bangalore, we produce quality and creative videos to our clients.

    ReplyDelete
  65. I must say this blog is much more informative for all services.

    modular kitchen dealers in Omr
    best modular kitchen dealers in Omr
    top modular kitchen dealers in Omr
    top modular kitchen dealers in OMR
    Modular kitchen in ECR
    top modular kitchen dealers in ECR
    modular kitchen dealers in ECR
    best modular kitchen dealers in ECR
    modular kitchen dealers in ECR
    modular kitchen showroom in ECR

    Sriman Interior

    ReplyDelete
  66. PVC Tarpaulin are the sheets that provide long-lasting protection to items that are being kept outside. We Supply a different variety of these Tarps. They are neither heavy nor light in terms of weight. They are made from not-so-heavy materials, but they last for many years without getting damaged. These sheets are also used where you need protection against UV light. They are popular for being used to cover hay grass and in agriculture where you need low weight Tarps to cover Agri products.

    ReplyDelete
  67. Hi Thank you for sharing this wonderful article. You describe all the points so well.
    Greetings from ATS Consultantx! We provide the E Filing Tax Portal under the supervision of professional consultants. Which allow to salary individuals or others to register and file their tax returns with an easy and affordable slant. The purpose of this affords to help taxpayers in order to mitigate their fear about FBR and empower them as responsible citizens of Pakistan.
    E Filing Tax Portal
    Salary Tax Calculator
    Business Tax Calculator
    Rental Tax Calculator
    Register NTN
    File My Return
    Benefits for filer
    ATS Services

    ReplyDelete
  68. Nice post really useful information. We are the leading website development services in dubai. Hire our web design agency in dubai today for web design services in dubai

    ReplyDelete
  69. Nice post it is really an interesting article.We are also providing the web design services in mumbai. We are the leading
    web design companies in mumbai
    website designers in mumbai

    ReplyDelete
  70. Our Waterproof Tarpaulin are also used to protect goods from rain, wind, and sunlight, and to keep the loads of open carts, trucks, and wood piles dry. These are best used as thermal covers that keep you warm and comfortable

    ReplyDelete
  71. Buy Tarpaulin Sheet From Buy Tarpaulins UK. We Supply a Variety of Tarpaulins such as Heavy Duty Tarpaulins & Waterproof Tarpaulins.

    ReplyDelete
  72. It's an amazing blog post found interesting facts about Testing AsyncTasks on Android, thanks for sharing important knowledge with us.
    https://thewebgross.com/social-media-marketing-services-delhi-india/

    ReplyDelete
  73. Great post really useful information. We are the leading web designing company in chennai. Hire our website development company in chennai today for best web design services in chennai.

    ReplyDelete
  74. Heavy-duty Tarpaulins are manufactured from high-quality polyethylene material. These Heavy Duty Tarpaulins come with aluminum eyelets and have meter intervals on all four sides. These covers are completely waterproof, rot-proof, shrink-proof and UV protected.

    ReplyDelete
  75. very nice blog.
    Best web designing company in Chennai
    web design Company in Chennai
    web designing company in Chennai
    web design Company in Chennai
    Website Design Company in Chennai
    Website designers in Chennai
    mobile application development web designers company in Chennai

    ReplyDelete
  76. Thanks for sharing the best information. Me and My team was learned more number of information about Mobile Application.
    couponsavinguae

    ReplyDelete
  77. I really enjoyed reading your blog. It was very well written and easy to understand. Unlike other blogs that I have read which are actually not very good. Thank you so much!FDM is one of the Online Reputation Management (ORM) Company in Chennai. For More Details Call us: 91+ 9791811111 or visit our website.



    ReplyDelete
  78. Evince Development has a team of expert responsive web designers who can understand the entire business strategy and then proceed further with professional responsive website design services

    ReplyDelete
  79. Great Post,thanks for sharing your knowledge with us this post helps many of us. we are the Top Web Development Company in Bangalore

    ReplyDelete
  80. Silver City Housing rawalpindi amp; Islamabad is an RDA-approved housing society located at Girja Road near Thalian Interchange, Islamabad Airport. It’s jointly developed by Laraib Associate and the SAREMCO Group.

    ReplyDelete
  81. Nice article and people also want to know about seo in lahore due to its elegancy.

    ReplyDelete
  82. SEO Service Pakistan is an in-house digital marketing agency that specializes in search engine optimization. The five-year journey that we've taken has helped us stay ahead of the pack, which is what makes us leaders in our industry. We are SEO experts and we work with our clients to help them generate revenue.

    ReplyDelete
  83. IMBMS (Indian Medical Business Management System) is one of the most active retail suppliers providing thorough supply of various personal care products. We believe in distributing
    imbms

    ReplyDelete
  84. Remarkable! Its really awesome paragraph, I have got much clear idea about from this post. if you want to visit my website: antalya sosyal medya ajansı

    ReplyDelete

  85. The blog on Test-Driven Development (TDD) for testing AsyncTasks on Android is a valuable guide for developers navigating the complexities of asynchronous programming. https://www.mobilezmarket.com/

    ReplyDelete