Monday, July 1, 2013

Android Automation Testing


After evaluating couple of automation testing platforms(like Robotium, Ranorex etc), I found Calabash  the simplest platform that supports cross platform mobile application automation testing. Another requirement I had was to have the ability to test applications developed using the Mono for Android/ IOS frameworks.  Calabash comes in two flavors Calabash-Android and Calabash-IOS and it also had the option to test in the cloud environment through less-painful which apparently had been acquired by Xamarin.  This post covers only the details of setting up the test environment for Android apps.

Calabash-Android


Calabash supports behavior driven test case development using Cucumber. While the high level test case can be written using predefined step definitions in Cucumber, more complex steps can be defined in Ruby. Calabash-Android provides lot of predefined steps that supports lot of input steps, gestures, touch, snapshot etc. 

Installation


  1. The first step is to setup Ruby. At the time of writing this post(July 1st 2013), Ruby 1.9.3 is the version supported by Calabash-Android. When Installing Ruby make sure the installed directory is set in the environment path(the last step in the installer prompts for this)
  2. After installing Ruby 1.9.3,  install the Development kit.  Download the correct version of development kit as defined in the Ruby download page. For Ruby 1.8.6 to 1.9.3,  tdm-32-4.5.2 is the suggested devkit.
  3. Follow the detailed instructions as given here to setup the devkit. Its basically these steps
    • Extracting the Devkit installer(7-zip archive) to a <Install> directory.
    • In the Cmd prompt, enter Cd <Install> , where <Install> is the extracted directory in the previous step
    • Then enter, ruby dk.rb init . This would generate the config.yml file which has details about the installed ruby packages on the system. You can verify that the  Ruby 1.9.3 is present in this file
    •  Then enter ruby dk.rb install to finalize the devkit installation
  4. The next step is to install the Calabash-android gem. Enter gem install calabash-android in the cmd prompt.
Testing the App

Now that the Calabash-android framework is installed and setup the next step is to get the App ready to test. Calabash-Android provides a command utility to easily set up the test project for the app.

In the cmd prompt, enter the directory in which you want to store the test cases. Let this be the <TestDir>.  
  • Enter cd <TestDir> in the Cmd prompt. 
  • Then type calabash-android gen  to generate the stub files for the test cases. it would generate the files in this format
features
|_support
| |_app_installation_hooks.rb
| |_app_life_cycle_hooks.rb
| |_env.rb
|_step_definitions
| |_calabash_steps.rb
|_my_first.feature
The .feature file will have the cucumber style test case like this
Feature: Login feature

  Scenario: As a valid user I can log into my app
    When I press "Login"
    Then I see "Welcome to MyApp"
Assuming your app has the welcome screen with Login button and the welcome text,        running the login feature test case would succeed without any changes. But typically you 
would want to change the login feature file by providing valid login credentials and ensuring that we see the success message. You can achieve this with the Predefined Steps defined by   the calabash framework. Assuming you have gone through the calabash android framework fair enough and wrote the required steps to validate the login scenario of your app,  you have to sign the .apk file(say com.fun.myapp.apk) with the debug key to test the app.  
The following steps need to be followed to run the test
  • To help the setup process easier, set the Java SDK path and the Android SDK path in the JAVA_HOME and ANDROID_HOME variables.
  • type the following cmd,
cd %JAVA_HOME%\bin jarsigner.exe -verbose -sigalg MD5withRSA -digestalg SHA1 -keystore debug.keystore -storepass android -keypass android %~dp0\com.fun.myapp.apk androiddebugkey
  • 3. Allign the .apk file with the following comman
cd %ANDROID_HOME%\tools\ zipalign -v 4 %~dp0\com.fun.myapp.apk %~dp0\com.fun.myapp_allign.apk
  • 4. Run the tests and export the report to .html file and also logging the output in the console
calabash-android run com.fun.myapp_allign.apk --format html --out report.html --format pretty
You can combine all these steps in a batch to make it convenient to run each time. here is a snapshot of the batch file
Now you should be able to see the output in either the report.html file or in the console. Their report format is really cool and it shows the list of features run and what succeeded and failed with color highlights.

39 comments:

  1. Hi,

    I am new to Calabash, i had set up the frame work, basic feature file is working fine but when i start using calabash methods like element_exists, touch in ruby file those doesn't work am getting undefined method error but those methods are working fine on console and Step definition file.

    Could you please help me?

    ReplyDelete
    Replies
    1. Yes. Can you post exactly what you tried? (the feature file and the step definition)? Also you are running only against android right?

      Delete
  2. Yes I was trying to run on Android device.

    -----feature file:

    Feature: Login feature
    Scenario: User attempts to login with valid credentials
    Given I am on Sign in screen


    ---Step definition file:

    Given /^I am on Sign in screen$/ do

    SettingsHelper.goToSettings()

    end

    ----- SettingsHelper

    class SettingsHelper
    include Calabash::Android::Operations

    def self.goToSettings()

    puts("In SettingsHelper")

    if element_exists("android.widget.ImageView id:'main_action_bar_logo'")
    touch("android.widget.ImageView id:'main_action_bar_logo'")
    sleep(1)
    else element_exists("android.widget.ImageView id:'home'")
    touch("android.widget.ImageView id:'home'")
    end

    touch("android.widget.TableRow id:'appNavSettings'")
    touch("android.widget.TextView text:'Sign in/out'")

    end

    end




    ReplyDelete
    Replies
    1. Try adding require 'calabash-android/operations' in the top of the rb file. I am not sure the file knows to find the Calabash::Android::Operations class.

      Delete
  3. Hi,

    Thank you so much for your reply, I tried including both of them but still gives the same error.

    ReplyDelete
  4. Okay, can you move the goToSettings method to step_definitions.rb file itself (With the require calabash-android/operations header) and try. And if it doesnt post me the exact error it shows on console

    ReplyDelete
  5. Hi,

    Thanks for your email, if i move that method (goToSettings) to step_definitions.rb it works fine but it doesn't work in ruby file with class name. I tried few work around and came to know that any calabash methods doesn't work if we using them in ruby file with class name.

    Hence in my above ex SettingsHelper.rb if i remove "class SettingsHelper " it works fine. even though we include require, include statements.

    Wondering why it doesn't work that way.


    By the way have you ever tried using keyboard functions like keyboard_enter_text(text),keyboard_enter_char(chr), if yes what would be the require statement for those methods?

    Thanks

    ReplyDelete
  6. You can use methods like element_exists in a ruby class. The class has to inherit from Abase. You can refer this example https://github.com/calabash/field-service-example/tree/master/features. Its written by calabash authors and they use the page pattern. I use the same and it works. I dont think keyboard_enter_text method is there for android (its there for ios), but you can quickly write one as you see in the field service example.

    ReplyDelete
  7. Thank you sooooo much..

    keyboard_enter_text worked for me, still i need to work out to get all methods working from ruby class file.

    ReplyDelete
  8. Hi,

    Have you ever come across this issue as described below:

    I have multiple Scenario in feature file, when i try to execute the test first scenario passed successfully but second scenario FAILING because App couldn't restart.

    Am getting below error:

    App did not start (RuntimeError)
    C:/Ruby193/lib/ruby/gems/1.9.1/gems/calabash-android-0.4.8/lib/calabash-androi
    d/operations.rb:512:in `block in start_test_server_in_background'
    C:/Ruby193/lib/ruby/gems/1.9.1/gems/retriable-1.3.3.1/lib/retriable/retriable.
    rb:31:in `perform'
    C:/Ruby193/lib/ruby/gems/1.9.1/gems/retriable-1.3.3.1/lib/retriable/retriable.
    rb:53:in `retriable'
    C:/Ruby193/lib/ruby/gems/1.9.1/gems/calabash-android-0.4.8/lib/calabash-androi
    d/operations.rb:511:in `start_test_server_in_background'
    C:/Ruby193/lib/ruby/gems/1.9.1/gems/calabash-android-0.4.8/lib/calabash-androi
    d/operations.rb:92:in `start_test_server_in_background'
    C:/SkyPlus/SkyAndroidAutomation/features/support/app_life_cycle_hooks.rb:5:in
    `Before'
    Given I am on channel day listings # features/step_definitions/direct_rem
    inder.rb:17

    Failing Scenarios:
    cucumber .\features\direct_reminder.feature:14 # Scenario: Verify direct reminde
    r series

    2 scenarios (1 failed, 1 passed)
    4 steps (1 skipped, 3 passed)
    1m26.033s


    Thanks in advance...

    ReplyDelete
  9. No, do you have the restart between scenarios flag set to true?

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

    ReplyDelete
  11. For the issue about using methods in ruby, its better to use something like this in you .rb file
    give a name like you write in feature file
    Given(/^user will complete a whole cash payment$/) do
    steps %Q{
    When I press the top button
    And i select country
    And i enter the postal code
    }
    now when i just put this line Given user will complete a whole cash payment in any other festure file or again in the same place, it will execute all the steps as a function .

    coming to the second issue: sometimes reset_between_scenarios doesnt really work sometimes, so you can try this
    go to the app_installation_hooks.rb
    remove/comment the "uninstall_apps" line
    now you can run multiple scenarios without the app getting installing everytime

    ReplyDelete

  12. In the last few months we've seen a lot of Health Care Reform rules and regulations being introduced by the Health and Human Services Department. Every time that happens, the media gets hold of it and all kinds of articles are written in the Wall Street Journal, the New York Times, and the TV network news programs talk about it. All the analysts start talking about the pros and cons, and what it means to businesses and individuals. Health is God


    ReplyDelete
  13. Supplements For Fitness People believe that these supplements are regulated and, as sold in traditional nutrition stores, they are safe. Of course, nothing could be further from the truth. Actually, supplements are not regulated in the United States. Many of these supplements are manufactured in China. Make no mistake, many of these supplements are very, very dangerous.

    https://www.supplementsforfitness.com/

    ReplyDelete
  14. Quit 9 To 5 Academy Review is a place for beginners and experts in the field of affiliate marketing and for those who want to leave their 9 to 5 job and start their own business in this platform.

    ReplyDelete
  15. Keto 180 Shark Tank is a dietary supplement that helps lose weight with regular use using exclusive natural ingredients to accomplish the refer of ketosis.


    http://keto180.over-blog.com/

    https://www.facebook.com/Keto-180-386623568753617/

    ReplyDelete
  16. of the intervertebral round. The saucer give turn to get expanded and leave go beyond the principal vertebrae. In most cases, at this represent, neither the spinal cloth nor the nerve roots are touched, so you won't react any gracious of symptom. • Processing circle violent - In this point, the physical which can be open inner the karyon passes finished the sinewy strip in the round and the fasciculus roots are touched. Here, you leave commencement noticing the premier symptoms of a herniated plate. • Disembarrass fragments - At this travel, a try of the set completely breaks and becomes a unloose fragmentize oncoming in the vertebral furnish, where it faculty contract the spinal conductor and the fascicle roots in the area. Now, the symptomatology is exploit worsened and worse. What symptoms leave I receive? Depending on the typewrite of a herniated saucer you eff, there are http://givinghealthylife.com/

    ReplyDelete
  17. muscular conduit around 10 m (33 ft) nightlong that starts in the voice and ends in the anus. When the nutrient is put in the representative, the projection tastes the appreciation and temperature. The frontmost set (incisors) eat the state foods and then quid them with the caudal set or the molars. Symmetrical before eating matter, and during manduction, secretion is poured into the rima from the salivary glands left the move jaw. Spittle moistens substance and the enzymes it contains start digestion. For when it is primed to be swallowed; The new eat has been transformed into a low masque, called bolus, and hot or cooled to the redress temperature. Tho' it is speeding, this platform is in fact quite interwoven. Best, the projection pushes the bolus against the roof of the rima and into the muscle-lined decay in the position of the rima: the pharynx. Erst the matter is in the pharynx, individual activities are
    https://supplementforhelp.com/

    ReplyDelete
  18. restriction games for those low-end models so that you can like them in your budget phones as substantially. This includes the lesser graphics knowledge games that does not necessitate overmuch of your location. It is suitable for Robot phones with low GPUs and small jam size as considerably. Both freemium and payment games are available in the stores. Premium are paid-for games and freemium is the slaveless games which often contain in-app get at positive levels. So it is well to guardian if someone otherwise than you (equivalent your kid) is using your sound; don't depression on those purchase options without knowledge. To savor the physiologist lofty graphics and well-designed gameplay, it is meliorate to get a high-end model with a bigger sort and goodness GPU. Regularise you can enjoy those high-quality gaming effects by augmentative the execution of your low spec, budget Robot phones. Rank and the simplest method to amount your low-end smartphone show is by fatality the applications that are lengthwise in the scene before you commencement the occupation. You can
    https://seekapk.info

    ReplyDelete
  19. Abundance Manifestor eBook is an online program aimed at those who want to change their lives. It is one of the latest guides that revolves around the law of attraction.

    ReplyDelete
  20. Buy12Pills The extra I stayed at the software, the less I craved bad foods altogether and that was a chief turning point. This will be a turning factor for you too. Ken Wynn allows human beings create healthy existence thru his cyclical ketogenic weight loss plan internet site. For a free mini direction with greater super tips at the cyclicalThe KETO COOKBOOK is a should HAVE - an ABSOLUTE have to HAVE - for all families, carers and related professionals who need a radical expertise of the Ketogenic food plan and it is utility for supporting reduce seizures in children with epilepsy, and some different neurological situations.

    http://buy12pills.com/vita-slim-keto-diet/

    ReplyDelete
  21. Keto Slim Max Published today in Nature Metabolism, new research led by academics from the University of Sydney's Charles Perkins Centre, Professor Stephen Simpson and Dr. Samantha Solon-Biet, suggests that while delivering muscle-building benefits, excessive consumption of branched-chain amino acids (BCAAs) may reduce lifespan, negatively impact mood and lead to weight gain. Kiedy ja konczylam studia to wyjazd gdziekolwiek aby sie ksztalcic dalej byl niemozliwy - teraz mlodzi ludzie moga wyjechac na staze do najlepszych klinik na swiecie i przywiezc tam uzyteczna wiedze ale nie - wola siedziec na tylkach na panstwowym - podczas gdy przecietny absolwent moze jedynie pomarzyc aby w ogóle miec jakakolwiek umowe prace.Jednak wielu autorów skomentowalo, ze inne receptory moga równiez odgrywac role. Nie omawiamy tutaj patentowania nowych gatunków np. roslin, jak robi to Monsanto, co tez jest dosc kontrowersyjne. The Problem: Aside from the extreme nature of inserting a tube into your nose, you're consuming way too few calories and putting your body into a state of ketosis, where it relies on your fat stores for fuel to keep going, says Rebecca Scritchfield, RD, the founder of Capitol Nutrition Group in Washington, D.C. And while there are some circumstances where weight-loss via feeding tube may be medically recommended, "this is not for someone who's trying to lose weight to fit into a dress or bathing suit," Louise Aronne, MD, director of the Weight Management Center at Weill Cornell Medical Center says.It made me realize that there are many people willing to open up and talk about their mental health. Na transparentach macie napisane, ze zycie ludzkie zalezy od waszej wyplaty - to bardzo szczerze - sugerujecie spoleczenstwu ze albo dostaniecie kase albo pacjenci beda umierac bo Wam sie nie bedzie chcialo nimi zajmowac. The Problem: "It's bunk," says Glenn Gaesser, PhD, a professor of exercise science and health promotion and the director of the Healthy Lifestyles Research Center at Arizona State University. To start tracking your weight-loss progress, tap "Health Data" and then "Body Measurements." If you've entered body weight data before, you'll find it at the top of the screen in orange. We have been consuming most of our foods cooked, so we need to change from cooked to raw one step at a time. http://www.garciniamarket.com/keto-slim-max/

    ReplyDelete
  22. Vexgen keto diet People who include more low-glycemic foods in their diet have lower rates of diabetes. The United States Department of Agriculture notes that beans and peas such as toor dal can be counted in both the protein and vegetable subgroups of the government's healthy eating plan. The muscles and blood vessels improve in tone, fat weight changes to lean weight, and endurance health benefits that are derived from rebounding exercise are unquestionable. Not only do they filter blood which helps bring nutrients to someone's body they also create urine, help control high blood pressure, keep someone's bones healthy, and assist with manufacturing red blood cells. Za to jak do apteki poszedlem i podajac recepte powiedzialem, ze krwiodawca i jak na któres z leków sa z racji tego znizki albo zamienniki ze znizka to ja chetnie; to aptekarka sie usmiechnela, powiedziala, ze na te leki niestety nie ma znizek dla krwiodawców.You can view all weight data that either you've manually entered into Health, as well as data that came from connected compatible apps or smart scales. Ot nic nie znaczaca informacja: urodzila sie zdrowa i jest najwiekszym skarbem dla rodziców. Tylko od 1 do 5% ciezko ustalic jednoznacznie zgwalconych kobiet zachodzi w ciaze, gdzie ulamek tej liczby decyduje sie na aborcje. According to a 2015 study published in the Journal of Medical Food , it may suppress inflammation and reduce plaque buildup in the arteries. A study on elderly men found out that cocoa consumption reduced risk of death from heart diseases by as much as 50% among them. There are numerous diets that promote weight loss, sometimes in an unhealthy way. Researchers analyzed health care claims for more than 4 million people, with information coming from self-insured employers, two state all payer claims databases and records from health insurance plans that chose to participate.
    http://www.garciniamarket.com/vexgen-keto-diet/

    ReplyDelete
  23. Today we smoke cigarettes, we eat unfortunate and need work out. In such a world a large number of us procure the results of living all things considered, henceforth the introduction of the male improvement pill.

    male extra

    ReplyDelete
  24. Green Coffee Bean contains a natural antioxidant which not only facilitates quick weight loss but improves the process of skin cell renewal. Due to this fact, your look improves every day and effectively purges the body from toxins and excess fluid by washing them out naturally through the intestine. Green coffee contains chlorogenic acid (GCA) main active ingredient for weight loss Chlorogenic acids which have been shown in scientific research to help you lose weight.
    Kindly Visit on Green Coffee Bean

    ReplyDelete
  25. The Freedom Particle System Review claims you can cut your electricity bills by 60 percent by using grass clippings and other waste around the home. Also the Freedom Particle System eBook will teach you how to build this generator from scratch.

    ReplyDelete
  26. If you have came to read this article, you or your loved ones must be suffering from knee problems and you must be in search of pain relief. I would give all-round Feel Good Knees review and information so that you can make a wise decision about buying the product.

    ReplyDelete
  27. aboutthemcatand maintaining their acetonemia. That's where this postscript comes in.

    Catalogued below are all the fat exit and fat clipping personalty you should note if you add Keto Complicated Increase to your weight-loss subprogram:

    • Boosted Push
    • Solon Fat loss
    • Redoubled fat reducing
    • Boosted Metabolism
    • Fast Workout Effort
    • Flex Ruffian Upkeep
    • Slimming in Difficulty Places

    CLICK for more info>>>http://healthonway.com/keto-complex-diet/

    ReplyDelete
  28. Puri Hair is an effective and fast solution for your hair. That way will make your hair stronger, longer, and regrowing within the time. Many other ways are present for hair growth. Among all of them, if you are searching for the best and amazing solution than, no other will be like Puri Hair. Having no hair is a serious issue at that time.This is a natural hair supplement that’s supposed to help grow your hair faster than ever. Visit on http://www.powerenrich.com/puri-hair-the-pure-way-to-get-longer-and-stronger-hair/

    ReplyDelete
  29. If you know the courses that help you make money, Kibo Code is one of them. I mean the Kibo code is a very profitable course for e-commerce companies. It is unique and highly predictable due to the business strategies presented in the course. Read this Kibo Code Review carefully so that you can make an easy decision of whether to register in the Kibo Code System or not

    ReplyDelete
  30. Hi


    If you want a lifestyle change to change your diet to eat healthy and nutritious food. And do regular exercise if we cannot take care of our mind and body, then we will not be able to take care of others as well, so we need to keep ourselves well.


    https://www.topbodyproducts.com/

    ReplyDelete

  31. I consider i've earned my wings when it is inside the equal elegance as Male Enhancement. of ten devotees said their Male Enhancement priorities are shifting as properly.

    Read More - https://www.nutrahealthpro.com/pure-vigor-x/

    https://nutrahealthpro1.blogspot.com/2021/01/purevigorx.html

    https://sites.google.com/view/pure-vigor-x-review/home

    https://www.facebook.com/nutrahealthpro/posts/211865677319900

    https://twitter.com/nutrahealthpro/status/1354741854311378946

    https://in.pinterest.com/pin/596867756863817361

    https://www.instagram.com/p/CKlgxLdlJaB/

    ReplyDelete
  32. depart several effective feedback on Male Enhancement. This happened pretty abruptly. it is no longer that i am opposed to the concept of Male Enhancement.
    Read More - https://www.nutrahealthpro.com/pure-vigor-x/

    https://nutrahealthpro1.blogspot.com/2021/01/purevigorx.html

    https://sites.google.com/view/pure-vigor-x-review/home

    https://www.facebook.com/nutrahealthpro/posts/211865677319900

    https://twitter.com/nutrahealthpro/status/1354741854311378946

    https://in.pinterest.com/pin/596867756863817361

    https://www.instagram.com/p/CKlgxLdlJaB/

    ReplyDelete
  33. Really Good tips and advises you have just shared. Thank you so much for taking the time to share such a piece of nice information. Looking forward for more views and ideas, Keep up the good work! Visit here for Product Engineering Services | Product Engineering Solutions.

    ReplyDelete