Tuesday 15 March 2016

Configure JUnit Testing Framework with Eclipse

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


3. Select Junit and Click Next


4. Select Junit4 and Click Finish

Running WebDriver Test in Different Browsers



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. 


package com.selenium.tests;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class BrowserTests {

 public static void main(String[] args) throws Exception {
  WebDriver driver=new FirefoxDriver();
  driver.get("http://qaautomated.blogspot.in");
  Thread.sleep(3000);
  driver.quit();
 }

}

For Selenium WebDriver 3 you need to download driver for firefox browser from HERE and use below code to launch firefox browser -


package com.selenium.tests;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class BrowserTests {

 public static void main(String[] args) throws Exception {
  WebDriver drive ;
System.out.println("launching firefox browser"); 
  System.setProperty("webdriver.gecko.driver", "C:\\Users\\Anuja.AnujaPC\\Downloads\\geckodriver.exe");
  driver = new FirefoxDriver();
driver.get("http://qaautomated.blogspot.in");
  Thread.sleep(3000);
  driver.quit();
 }

}



Running Test in Chrome 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.


package com.selenium.tests;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class BrowserTests {

 public static void main(String[] args) throws Exception {
  System.setProperty("webdriver.chrome.driver", "C:\\Users\\Anuja.AnujaPC\\Downloads\\chromedriver_win32\\chromedriver.exe");
  WebDriver driver=new ChromeDriver();
  Thread.sleep(1000);
  driver.get("http://qaautomated.blogspot.in");
  Thread.sleep(3000);
  driver.quit();
 }

}

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.



package com.selenium.tests;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;

public class BrowserTests {

 public static void main(String[] args) throws Exception {
  
   DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
   capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
   System.setProperty("webdriver.ie.driver", "C:\\Users\\Anuja.AnujaPC\\Downloads\\IEDriverServer.exe");
   WebDriver driver = new InternetExplorerDriver(capabilities);
   driver.manage().window().maximize();
   driver.get("http://qaautomated.blogspot.in");
   
   driver.quit();
   }
 }

I hope this post guide everyone who is looking to launch selenium webdriver test cases on different types of browsers.

Setting up Selenium in Eclipse IDE


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.

1. Download latest version of JDK from HERE.
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


Now your Java setup is ready.

Step 2 - Download Eclipse from this Link.http://www.eclipse.org/downloads/
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.

Appium Setup in Android Studio with TestNG



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 -

  1. Download -
    1. Android Studio
    2. Appium Jar files
    3. Latest Appium Client Library
  2. Install Android Studio -click here
  3. Open android studio and create a new project - How to create android project?
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 -


 testCompile 'org.assertj:assertj-core:2.0.0'
    testCompile 'org.testng:testng:6.9.10'

TestNG Gradle Dependency
TestNG Gradle Dependency

6. Add below TestNG test case by creating new Java Class in src->main


public class TestNGSampleTestCase{

AppiumDriver driver;

@BeforeTest
    public void testCaseSetup()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);

    }

@Test
    public void testSeekBar()throws  Exception
    {
           //Locating seekbar using resource id
            WebElement seek_bar=driver.findElement(By.id("seek_bar"));
            // get start co-ordinate of seekbar
            int start=seek_bar.getLocation().getX();
            //Get width of seekbar
            int end=seek_bar.getSize().getWidth();
            //get location of seekbar vertically
            int 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");
    }
@AfterTest
    public void testCaseTearDown()
    {
        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.

Friday 11 March 2016

How to Match Child View of a View in Espresso



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.


@Test
public void testChildView()
{
onData(withItemContent("Dog"))
  .onChildView(withId(R.id.no_char))
  .perform(click());
}

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

Espresso Resource Idling Example


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;

import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.VisibleForTesting;
import android.support.test.espresso.IdlingResource;
import android.support.test.espresso.idling.CountingIdlingResource;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.example.android.testing.espresso.IdlingResourceSample.IdlingResource.SimpleIdlingResource;

/**
 * Gets a text String from the user and displays it back after a while.
 */
public class MainActivity extends 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.
    @Nullable private SimpleIdlingResource mIdlingResource;

    @Override
    protected void onCreate(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);
    }

    @Override
    public void onClick(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);
        }
    }

    @Override
    public void onDone(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
    @NonNull
    public 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
 Espresso.unregisterIdlingResources(mIdlingResource);



/*
 * 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;

import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.action.ViewActions.closeSoftKeyboard;
import static android.support.test.espresso.action.ViewActions.typeText;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;

import android.support.test.espresso.Espresso;
import android.support.test.espresso.IdlingResource;
import android.support.test.filters.LargeTest;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;

import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;


/**
 * Same as Espresso's BasicSample, but with an Idling Resource to help with synchronization.
 */
@RunWith(AndroidJUnit4.class)
@LargeTest
public class ChangeTextBehaviorTest {

    private static final String STRING_TO_BE_TYPED = "Espresso";

    @Rule
    public ActivityTestRule<MainActivity> mActivityRule = new ActivityTestRule<>(
            MainActivity.class);

    private IdlingResource mIdlingResource;

    @Before
    public void registerIdlingResource() {
        mIdlingResource = mActivityRule.getActivity().getIdlingResource();
        // To prove that the test fails, omit this call:
        Espresso.registerIdlingResources(mIdlingResource);
    }

    @Test
    public void changeText_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)));
    }

    @After
    public void unregisterIdlingResource() {
        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 :-)
 

Tuesday 8 March 2016

How to log test cases in Android Studio


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.


public void TestCase
{
AppiumDriver driver;
String Tag_name="ScrollTestCase";
@Before
    public void testCaseSetup()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);

    }

@Test
    public void testVerticalScroll()
    {
        //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")
        }
    }
@After
    public void testCaseTearDown()
    {
        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 test case in Andorid Studio
Log Appium Test Execution Report

6. Then click on Edit Filter Configuration as shown below.

Log Appium Test Case in Android Studio
Check logs in Android Studio

7.Enter Filer name and our Tag name hit OK.

Log Appium Test Case in Android Studio
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 :-)






Monday 7 March 2016

How to Take Screenshot in Appium ?



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.


public void CaptureScreenShot
{
    AppiumDriver driver;
    String folder_name;
    DateFormat df;
   @Before
    public void testCaseSetup()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);

    }
    @Test
    public void testSeekBar()throws  Exception
    {
           //Locating seekbar using resource id
            WebElement seek_bar=driver.findElement(By.id("seek_bar"));
            // get start co-ordinate of seekbar
            int start=seek_bar.getLocation().getX();
            //Get width of seekbar
            int end=seek_bar.getSize().getWidth();
            //get location of seekbar vertically
            int 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();
    }
    public void captureScreenShots() 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 name
        new File(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));
    }
    @After
    public void testCaseTearDown()
    {
        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.


public void CaptureScreenShot
{
    AppiumDriver driver;
    String folder_name;
    DateFormat df; 
    @Before
    public void testCaseSetup()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);

    }
    @Test
    public void testSeekBar()throws  Exception
    {
           //Locating seekbar using resource id
            WebElement seek_bar=driver.findElement(By.id("seek_bar"));
            // get start co-ordinate of seekbar
            int start=seek_bar.getLocation().getX();
            //Get width of seekbar
            int end=seek_bar.getSize().getWidth();
            //get location of seekbar vertically
            int 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");
    }
   public void captureScreenShots(String file_name) throws IOException {
        folder_name="screenshot";
        File f=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        //create dir with given folder name
        new File(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));
    }
    @After
    public void testCaseTearDown()
    {
        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 :-)