Hi everyone this is going to be very short and simple. We are going to configure our Eclipse project to write and run our test cases with Junit framework. Junit is very commonly used testing framework and if you don not want to use Junit then you can also go with TestNG framework. In this post we will focus of Junit.
It is just simple 2 minutes job to configure Junit if you follow below steps -
1. Right Click on you project in eclipse.
2. Click on Properties -> Build Path -> Add Libraries
Once you are done with setup of eclipse project with Selenium WebDriver as shown in the previous tutorial then you are now ready to add your own test cases.But before adding test cases we will see how we can run our test cases on different browsers like firefox, chrome and Internet Explorer.
As we have created project with name BasicSelenium we need to create a class where we can write our test cases.
Video Tutorial -
1. Right click on BasicSelenium project -> create new package named "com.selenium.tests".
2. Right click on BasicSelenium project -> create mew java class with name "BrowserSample".
3. Add main method in the class as we know in java execution starts from main method.
4. Running the code is simple you can click on Run button at the top bar or right click on Java class and click on Run.
Running Test in FireFox Browser -
Copy the below code inside main method. Let us now understand what the below code does. The first line of code is responsible for launching FireFox browser. Then pass the url which you want to open and then stop the driver.
This is simple scenario where you want to open a particular url in FireFox Browser.
One of the advantage of Selenium WebDriver is that it Supports Multiple Browsers and hence we can test with chrome browser as well. You can use below code for launching chrome browser and opening the url of your choice, but first you need to download chromedriver from HERE.
Running Test in Internet Explorer - As we downloaded chromedriver to run our selenium webdriver test on Chrome browser similarly we will need IEDriver which you can download HERE.Extract the zip folder and note down the path.Apart from this we need to set some capabilities so that we can open url in IE. Refer code given below.
Hi all even though SETUP sound like a big word but when it comes to setting up Selenium WebDriver it is very simple and easy and I am here to give you simplest way to do it. In this post we will learn the selenium WebDriver setup for windows. Follow the below steps and then you are good to go.
Video Tutorial -
Step1 - Install JDK. This is the first thing you need to do and below are the steps to install JDK.
2. Click on "Accept License Agreement" and download latest code.
3. Click on .exe file and then java installation window will open.
4. click on next and finish installation.
5. Installation deosn't complete unless you set JAVA_HOME. to so go to my computer properties.
6. Click on Advanced System Settings -> Environment Variables -> Edit and then in Variable Name - "JAVA_HOME" and variable value-" C:\Program Files\Java\jdk1.7.0_79
There is nothing more to do in installing eclipse as you just need to extract the folder and launch eclipse IDE using eclipse.exe.
Step 3 - Download Selenium WebDriver Java Client from HERE.Extract the folder and store in your system with folder c:\selenium_jars
Step 4 - Configure Eclipse with Selenium WebDriver.
1. Click on eclipse.exe
2. Enter Workspace name and click on OK.
3. Create new java project by File-> New -> Project -> Java Project.
4. Enter Project Name and click on Finish.
5. Right click on the created Project Name then go properties- > java build path -> Libraries->Add External Jars.
6. Add 2 jars from c:\selemiun_jar folder and all the jars from c:\selenium/-jar\libs\ folder.
7.Click on OK.
Now your project Eclipse Project in configured with Selenium WebDriver and you can start writing your test cases. It was very simple setup and of you face any kind of issues with this do post your questions in for of comments and I will try my level best to provide soulution.
Hi all, I hope you all are doing well. I have posted an article about Setting Up Appium Server with Android Studio. I felt very glad as thousands of people visited this post and found it useful. As I explained how to use JUnit Testing Framework in my previous post , so now in this post you will learn about using TestNG framework in Android Studio.
Video -
I request you to go through my previous page and do the exact same steps as per below recap -
4.
Add the Appium jars into your project - click on project -> click on
app->copy all the jars in lib. Select the copied jars except
Selenium, Java client and Junit Jar ,then right click on it and click on
"Add as Library".
5. Click on build.gradle in app you will see all the libs added like below. But you need to Add TestNG specific Libs given below -
6. Add below TestNG test case by creating new Java Class in src->main
publicclassTestNGSampleTestCase{
AppiumDriver driver;@BeforeTestpublicvoidtestCaseSetup()throws Exception
{
DesiredCapabilities cap=new DesiredCapabilities();
cap.setCapability(MobileCapabilityType.PLATFORM_NAME,"Android");
cap.setCapability(MobileCapabilityType.DEVICE_NAME,"Android device");
cap.setCapability(MobileCapabilityType.NEW_COMMAND_TIMEOUT,"4000");
cap.setCapability(MobileCapabilityType.APP,"c://apks//seekbarsample.apk");
cap.setCapability("noReset",true);
driver =new AndroidDriver(new URL("http://127.0.0.1:4723/wd/hub"), cap);}@TestpublicvoidtestSeekBar()throws Exception
{//Locating seekbar using resource id
WebElement seek_bar=driver.findElement(By.id("seek_bar"));// get start co-ordinate of seekbarint start=seek_bar.getLocation().getX();//Get width of seekbarint end=seek_bar.getSize().getWidth();//get location of seekbar verticallyint y=seek_bar.getLocation().getY();// Select till which position you want to move the seekbar
TouchAction action=new TouchAction(driver);//Move it will the end
action.press(start,y).moveTo(end,y).release().perform();//Move it 40%int moveTo=(int)(end*0.4);
action.press(start,y).moveTo(moveTo,y).release().perform();
captureScreenShots("Seekbar");}@AfterTestpublicvoidtestCaseTearDown(){
driver.quit();}}
7. Running the TestNG test case
Click on build variant
Select Unit Testing
Start the appium server with Specific port "4444"click here
Connect device with USB debugging on or start an emulator.
Right click on the test class and click on "Run".
I hope this tutorial helps and in case you have any queries do post it as a comment.
Hi all clicking on child view of a view is mostly used in case ListView whenever we want to click on the perticular column or part inside the row. We have already seen a ListView Example in the previous post where we had around 50 rows containing text and toggle button. We will just use the same example and learn how to match a child view inside a view in espresso.
App Under Test -
Consider that we have a app with ListView and the ListView is divided into two columns the first column is text and second column is number of characters in the text.The list view has unique text in first column but second column has repetitive entries.
Test Case Scenario-
1. check one row in list where with Text "Dog" and "3".
2. click on 3 where 3 has occurred multiple times for different rows but we want to click on "3" within the row with text "Dog.
Test Case -
As you all are already familiar with espresso. I am just giving you the below simple test case to achieve our test case goal.
I hope this post helps you find your code coverage for your test suit :)
Please Share your feedback in comments section below and follow QA Automated to get latest post update.Happy Testing :-)
The advantage of Espresso is its ability to seamlessly synchronize all test operations with the application being tested. By default, Espresso waits for UI events in the current message queue to be handled and for default instances of AsyncTask to complete before it moves on to the next test operation.
However, there are instances where applications perform background operations, such as communicating with web services, using non-standard means, such as direct creation and management of threads.
In such cases, you have to use idling resources to inform Espresso of the app’s long-running operations.
1. Modify java class MainActivity.java inside app->src->Main.
2. Add method getIdlingResource() as shown in below example.
package com.example.android.testing.espresso.IdlingResourceSample;importandroid.app.Activity;importandroid.os.Bundle;importandroid.support.annotation.NonNull;importandroid.support.annotation.Nullable;importandroid.support.annotation.VisibleForTesting;importandroid.support.test.espresso.IdlingResource;importandroid.support.test.espresso.idling.CountingIdlingResource;importandroid.view.View;importandroid.widget.EditText;importandroid.widget.TextView;importcom.example.android.testing.espresso.IdlingResourceSample.IdlingResource.SimpleIdlingResource;/** * Gets a text String from the user and displays it back after a while. */publicclassMainActivityextends Activity implements View.OnClickListener,
MessageDelayer.DelayerCallback{// The TextView used to display the message inside the Activity.private TextView mTextView;// The EditText where the user types the message.private EditText mEditText;// The Idling Resource which will be null in production.@Nullableprivate SimpleIdlingResource mIdlingResource;@OverrideprotectedvoidonCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);// Set the listeners for the buttons.
findViewById(R.id.changeTextBt).setOnClickListener(this);
mTextView =(TextView) findViewById(R.id.textToBeChanged);
mEditText =(EditText) findViewById(R.id.editTextUserInput);}@OverridepublicvoidonClick(View view){// Get the text from the EditText view.final String text = mEditText.getText().toString();if(view.getId()== R.id.changeTextBt){// Set a temporary text.
mTextView.setText(R.string.waiting_msg);// Submit the message to the delayer.
MessageDelayer.processMessage(text,this, mIdlingResource);}}@OverridepublicvoidonDone(String text){// The delayer notifies the activity via a callback.
mTextView.setText(text);}/** * Only called from test, creates and returns a new {@link SimpleIdlingResource}. */@VisibleForTesting@NonNullpublic IdlingResource getIdlingResource(){if(mIdlingResource ==null){
mIdlingResource =new SimpleIdlingResource();}return mIdlingResource;}}
3. Register one or more of your idling resources with
Espresso by calling Espresso.registerIdlingResource() in the test setup and then in teardown we should unregister using code
/* * Copyright 2016, The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package com.example.android.testing.espresso.IdlingResourceSample;importstatic android.support.test.espresso.Espresso.onView;importstatic android.support.test.espresso.action.ViewActions.click;importstatic android.support.test.espresso.action.ViewActions.closeSoftKeyboard;importstatic android.support.test.espresso.action.ViewActions.typeText;importstatic android.support.test.espresso.assertion.ViewAssertions.matches;importstatic android.support.test.espresso.matcher.ViewMatchers.withId;importstatic android.support.test.espresso.matcher.ViewMatchers.withText;importandroid.support.test.espresso.Espresso;importandroid.support.test.espresso.IdlingResource;importandroid.support.test.filters.LargeTest;importandroid.support.test.rule.ActivityTestRule;importandroid.support.test.runner.AndroidJUnit4;importorg.junit.After;importorg.junit.Before;importorg.junit.Rule;importorg.junit.Test;importorg.junit.runner.RunWith;/** * Same as Espresso's BasicSample, but with an Idling Resource to help with synchronization. */@RunWith(AndroidJUnit4.class)@LargeTestpublicclassChangeTextBehaviorTest{privatestaticfinal String STRING_TO_BE_TYPED ="Espresso";@Rulepublic ActivityTestRule<MainActivity> mActivityRule =new ActivityTestRule<>(
MainActivity.class);private IdlingResource mIdlingResource;@BeforepublicvoidregisterIdlingResource(){
mIdlingResource = mActivityRule.getActivity().getIdlingResource();// To prove that the test fails, omit this call:
Espresso.registerIdlingResources(mIdlingResource);}@TestpublicvoidchangeText_sameActivity(){// Type text and then press the button.
onView(withId(R.id.editTextUserInput)).perform(typeText(STRING_TO_BE_TYPED), closeSoftKeyboard());
onView(withId(R.id.changeTextBt)).perform(click());// Check that the text was changed.
onView(withId(R.id.textToBeChanged)).check(matches(withText(STRING_TO_BE_TYPED)));}@AfterpublicvoidunregisterIdlingResource(){if(mIdlingResource !=null){
Espresso.unregisterIdlingResources(mIdlingResource);}}}
I hope this post helps you find your code coverage for your test suit :)
Please Share your feedback in comments section below and follow QA Automated to get latest post update.Happy Testing :-)
Logging
test case results is as important as writing test cases. There are many
ways to log the results provided by JUnit but I am going to provide a
simple and effective solutions which I adopted to Log Test case results
on Android Studio.This method is independent of selection of automation
tool.
It
is also a good practice to take a screenshot from the device when test
case fails but that code is tool dependent so I will share that too in
future posts.
The
way you log your test case results will simplify tracking of bugs and
generate a proper report as output of your Test Suit Run.Hence I suggest
you to start Logging your test case results starting from your very
first test case.
Let us see with simple example.
1. Create a Java Class names TestCases in the Android Studio.
2. Declare a Tag in the class as String LoginTestCase.
3. Then write the log on sucess or failure as per you like as shown in below test case. I have added Appium test case as sample but this you can use in any of your Test Cases.
publicvoid TestCase
{
AppiumDriver driver;
String Tag_name="ScrollTestCase";@BeforepublicvoidtestCaseSetup()throws Exception
{
DesiredCapabilities cap=new DesiredCapabilities();
cap.setCapability(MobileCapabilityType.PLATFORM_NAME,"Android");
cap.setCapability(MobileCapabilityType.DEVICE_NAME,"Android device");
cap.setCapability(MobileCapabilityType.NEW_COMMAND_TIMEOUT,"4000");
cap.setCapability(MobileCapabilityType.APP,"c://apks//seekbarsample.apk");
cap.setCapability("noReset",true);
driver =new AndroidDriver(new URL("http://127.0.0.1:4723/wd/hub"), cap);}@TestpublicvoidtestVerticalScroll(){//Scroll till the 25th row
driver.scrollTo("List item:25");//Click on the 25th row text
driver.findElement(By.name("List item:25")).click();try{
Log.e(Tag_name,"Test case passes");
Assert.assertEquals("Clicked on row no: 25", driver.findElement(By.id("row_select")).getText());}catch(AssertionError e){
Log.e(Tag_name,"Test case failed")}}@AfterpublicvoidtestCaseTearDown(){
driver.quit();}}
4. Once you are done adding adding log in each test case ten run the test suite.
5. Then click on Android Monitor at the and it will open the Monitor as shown in below screenshot
Log Appium Test Execution Report
6. Then click on Edit Filter Configuration as shown below.
Check logs in Android Studio
7.Enter Filer name and our Tag name hit OK.
Filter Logs in Android Studio
8. Then you can read your test case logs.
I hope you find this tutorial useful. Do share your feedback and
questions in comments section below.Please follow QA Automated on social media to
get latest post updates. Happy Testing :-)
In any android automation tool capturing screenshot is very important part.In any android test suit if you take screenshot during your test failures then you can identify and capture the defect very quickly and effectively. The same screenshot you can share with developers to report your bug. Taking screenshot while running your automation tool saves lot of time for tester. In this post we will learn how we can take screenshot for our appium test case failure.
Check out the simple example which I have prepared for taking screenshot in appium test case failure. First create a method to captureScreenShot() in this method you can decide how you are going to name your directories and .png files for each screenshot. You can use date or testcase name to uniquely name your .png files.
In the below test case we will store our screenshots in the folder/dir named as screenshot. I will show you two ways to store the screen shot first using current date and secondly using any name for your choice.
Video Tutorial -
First Method-
1. Use interface given by Web Driver "TakeScreenShot".
2. Get current date and time using DateFormat class.
3. Then store the it in screenshot folder with name set to current date and time.
@BeforepublicvoidtestCaseSetup()throws Exception
{
DesiredCapabilities cap=new DesiredCapabilities();
cap.setCapability(MobileCapabilityType.PLATFORM_NAME,"Android");
cap.setCapability(MobileCapabilityType.DEVICE_NAME,"Android device");
cap.setCapability(MobileCapabilityType.NEW_COMMAND_TIMEOUT,"4000");
cap.setCapability(MobileCapabilityType.APP,"c://apks//seekbarsample.apk");
cap.setCapability("noReset",true);
driver =new AndroidDriver(new URL("http://127.0.0.1:4723/wd/hub"), cap);}@TestpublicvoidtestSeekBar()throws Exception
{//Locating seekbar using resource id
WebElement seek_bar=driver.findElement(By.id("seek_bar"));// get start co-ordinate of seekbarint start=seek_bar.getLocation().getX();//Get width of seekbarint end=seek_bar.getSize().getWidth();//get location of seekbar verticallyint y=seek_bar.getLocation().getY();// Select till which position you want to move the seekbar
TouchAction action=new TouchAction(driver);//Move it will the end
action.press(start,y).moveTo(end,y).release().perform();//Move it 40%int moveTo=(int)(end*0.4);
action.press(start,y).moveTo(moveTo,y).release().perform();
captureScreenShots();}publicvoidcaptureScreenShots()throws IOException {
folder_name="screenshot";
File f=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);//Date format fot screenshot file name
df=new SimpleDateFormat("dd-MMM-yyyy__hh_mm_ssaa");//create dir with given folder namenewFile(folder_name).mkdir();//Setting file name
String file_name=df.format(new Date())+".png";//coppy screenshot file into screenshot folder.
FileUtils.copyFile(f,new File(folder_name +"/"+ file_name));}@AfterpublicvoidtestCaseTearDown(){
driver.quit();}}
Second method-
1. Use interface given by Web Driver "TakeScreenShot".
2. Get the name from test case calling captureScreenShot() method.
3. Then store the it in screenshot folder with name set to the string passes by test case.
@BeforepublicvoidtestCaseSetup()throws Exception
{
DesiredCapabilities cap=new DesiredCapabilities();
cap.setCapability(MobileCapabilityType.PLATFORM_NAME,"Android");
cap.setCapability(MobileCapabilityType.DEVICE_NAME,"Android device");
cap.setCapability(MobileCapabilityType.NEW_COMMAND_TIMEOUT,"4000");
cap.setCapability(MobileCapabilityType.APP,"c://apks//seekbarsample.apk");
cap.setCapability("noReset",true);
driver =new AndroidDriver(new URL("http://127.0.0.1:4723/wd/hub"), cap);} @TestpublicvoidtestSeekBar()throws Exception
{//Locating seekbar using resource id
WebElement seek_bar=driver.findElement(By.id("seek_bar"));// get start co-ordinate of seekbarint start=seek_bar.getLocation().getX();//Get width of seekbarint end=seek_bar.getSize().getWidth();//get location of seekbar verticallyint y=seek_bar.getLocation().getY();// Select till which position you want to move the seekbar
TouchAction action=new TouchAction(driver);//Move it will the end
action.press(start,y).moveTo(end,y).release().perform();//Move it 40%int moveTo=(int)(end*0.4);
action.press(start,y).moveTo(moveTo,y).release().perform();
captureScreenShots("Seekbar");}publicvoidcaptureScreenShots(String file_name)throws IOException {
folder_name="screenshot";
File f=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);//create dir with given folder namenewFile(folder_name).mkdir();//Setting file name
file_name=df.format(new Date())+".png";//coppy screenshot file into screenshot folder.
FileUtils.copyFile(f,new File(folder_name +"/"+ file_name));}@AfterpublicvoidtestCaseTearDown(){
driver.quit();}}
I hope this tutorial will help you take screen shots in your appium test case.
With this tutorial you can write test code for taking screenshot when you are appium test case fails, taking screenshot for verifying UI on multiple devices.
I hope you find this tutorial useful. Do share your feedback and
questions in comments section below.Please follow QA Automated on social media to
get latest post updates. Happy Testing :-)