Search This Blog

Tuesday, 3 November 2015

Intellij Idea Shortcuts

Shortcuts @ work to save your time and add fun

When it comes to success, there are no shortcuts.

While I was at work, I realized a very strange fact. A question rose in my mind and the asked myself about "What is the most repetitive task I do..??"

Very specific to work on a Windows machine, I always grab the small little mouse to move the cursor across the two monitors connected to my Computer. Switching Windows, Switching Tabs on a browser, Browsing directories, and many more common tasks to accomplish the day to day activities.

Along with these stuff, I spend a lot of time on IntelliJ Idea which is one of the most flexible tool for working with programming. This tool has so many features, works with version control tools, build configuration tools, java plugins, (what not...!!) and many more.

I thought sharing few experiences with this tool which might be helping others to save a minute of their daily tight-packed days..

Thinking how a simple key-board shortcut will save time..???
Give a try.. It doesn't take much effort...

Tip #1
Every time we load the IntelliJ Idea tool, there is a wizard showing "Tip of the day".




Don't ignore this pop-up.
May be the task which we spend 5 mins, could be done in a min by following the options given in the tool.

A lot can be made by just adding "A bit a day"



Tip #2
I realized that few handy shortcuts were placed just on the landing page of the tool.
(which I never cared to look at. After an year of using this tool, found the existence of these shortcuts which made my life simpler)



(To see these, close all the file/tabs in the IntelliJ Idea)

Tip #3
Then, here comes the general shortcuts which are always mentioned very next to the traditional menu options.
Most of the actions listed in the menus are mapped with keyboard shortcuts.


Tip #4
Last but not the least, there is a "KeyMap" configuration setting available in the Settings wizard.
Using this wizard, one can search/create/update/modify the shortcuts for the actions interested in.

A shortcut to launch the settings window "ctrl + alt + s"
Then search for "KeyMap" in the settings wizard, which looks like in the below screenshot



The Keymap gives option to customize the shortcuts to the extent depending on user interests.
The tool is smart enough to enable users to migrate from different other IDEs. IntelliJ can be configured to mimic the behaviour of other IDEs.

If a user had experience working with NetBeans, and new to the IntelliJ, it will be tough to correct everytime after hitting a shortcut which works for NetBeans.

Idea IDE gives an option to change the shortcut templates.

How encouraging it is to import our shortcut key combinations from a different tool. I love this feature a IDEA. 


Give a try to look at these help screens, and make it a routine in day to day life to use atleast one single NEW shortcut a day.

Happy programming...

Sunday, 1 November 2015

TestNg Data Provider Annotation


While executing test cases with a multiple data sets, it is always ideal to parameterize the test cases.

The parameterization of the test data is always a smart task to be taken into consideration based on number of parameters like
 - Number of Iterations
 - Frequency of data is updated
 - Maintenance of test data
 - and many more...


Using TestNg, we can achieve this in multiple ways like
 - Passing as an input from the XML file
 - Using the DataProvider annotation

Using XML configuration, we can configure the variable and data in the xml as shown below:
<parameter name="username"  value="Martin">

And in the Test, the variable can be used like this :


@Parameters({ "username" })
@Test
public void testSingleString(String firstName) {
  System.out.println("Invoked testString " + firstName);
  assert "Martin".equals(firstName);
}



Passing data to the Test using @DataProvider annotation in TestNg
Code snippet to create the test data

@DataProvider(name = "sample")
public static Object[][] getData() {
 // Any code to fetch data.
 Object[][] a = { 
   { 1, "name" }, 
   { 2, "Place" },
   { 3, "email" },
   { 4, "skype" }
   };
 return a;
}

And the test looks like this:

 @Test(dataProvider = "sample")
 public static void runTest(int number, String s) {
  System.out.println("The value of a is : " + number + " and the string is : " + s);

 }
The output will be shown as :



Friday, 23 October 2015

Capture full screen screenshot using Selenium + Java

It is always a good idea to have a screenshot for investigating what was the state of the application at the time of exception/halt of execution.

Although Selenium WebDriver provides default functions to take the screenshots of the browser at the exception. See example here

The alternate is to capture the full screenshot (Screenshot covering the full desktop) at the time of exception or error occurred on the screen.

Note: When the test execution is failing because of "Model Pop Up" on the browser, default function of the WebDriver will not be able to capture the Model Pop Up in the screenshot.

Git Hub Link



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

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;

public class FullScreenShot {
    final static String fileLocation = "D:\\ScreenShot\\";


    public static void main(String[] args) {
        try {
            WebDriver driver = new FirefoxDriver();
            driver.get("http://www.testautomation4all.com");
            driver.findElement(By.id("some-non-existing-element")).click();
        } catch (Exception e) {
            captureEnirePageScreenshot("Unexpected error");
        }

    }

    public static void captureEnirePageScreenshot(String screenShotName) {
        try {
            // Capture the dimensions of the screen
            Dimension d = Toolkit.getDefaultToolkit().getScreenSize();

            // Convert the dimensions into rectangle object type
            Rectangle rec = new Rectangle(d);

            // Take the screenshot using the Robot instance
            Robot robot = new Robot();

            BufferedImage myImage = robot.createScreenCapture(rec);

            File img = new File(fileLocation + screenShotName + ".png");

            ImageIO.write(myImage, "png", img);

            System.out.println("Done");

        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}

How to Print Google Search result in the Eclipse Console?

Example to extract the text from google search result

To extract the search result count (which is displayed on the top) from the google search result, we have to

  1.  Find the WebElement of the search result and extract the WebElement
  2. The resulted string (result) is having extra characters like "About 5050 results"
  3. Extract the sub string from the obtained result string
  4. Replace all the extra characters from the result string
  5. Now parse the String to number format to convert the string to number.
GitHub Url

The program for the above example is as below



import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.Selenium;

public class GoogleSearchResult {
    public static void main(String[] args) throws InterruptedException {
        Selenium selenium = new DefaultSelenium("localhost", 4444, "firefox", "http://www.google.com/");
        selenium.start();
        selenium.open("/?gws_rd=ssl");
        selenium.type("//input[@id='lst-ib']", "test automation 4 all");
        selenium.click("name=btnG");
//        selenium.waitForPageToLoad("30000");
        Thread.sleep(2000);
        String result = selenium.getText("id=resultStats");
        System.out.println("The Raw format" + result);

        result = result.substring(7, result.indexOf("result"));
        System.out.println("After extracting the substring of the result : " + result);

        result = result.replaceAll(",", "").trim();
        System.out.println("Removing the extra characters from the remaining string " + result);

        System.out.println("Now the remaining string is in the String format. Converting them to the Integer format");
        int searchResultCount = Integer.parseInt(result);

        System.out.println("Total Number of search results : " + searchResultCount);

        selenium.stop();
    }

}

Thursday, 22 October 2015

Page Object Model - Example


An example to create a small validation test using Page Object Model

All we will need for this are
  1. One class file for every Page (Page Objects will be defined in this class)
  2. One class file for invoking/writing the tests
Lets start creating the Page Object file
(To make life simpler, I've opted to write a test the google Home page and the Search Result Pages)

This is the Home Page related Class File

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class HomePageTest {
    final String xpathToLogo = "";
    final String xpathToSearchBox = "";
    final String xpathToSearchButton = "";
    final String xpathToImFeelingLuckyButton = "";
    final String xpathToAboutLink = "";
    final String xpathToGmailLink = "";
    final String xpathToImagesLink = "";
    final String xpathToSearchResult = "";

    WebDriver driver = new FirefoxDriver();

    @Before
    public void setUpBrowser() {
        driver.get("http://www.google.com");
    }

    @Test
    public void validateHomePageElements() {
        Assert.assertTrue("Logo is not displayed", driver.findElement(By.xpath(xpathToLogo)).isDisplayed());
        Assert.assertTrue("Search text box is not displayed", driver.findElement(By.xpath(xpathToSearchBox)).isDisplayed());
        Assert.assertTrue("Search Button is not displayed", driver.findElement(By.xpath(xpathToSearchButton)).isDisplayed());
        Assert.assertTrue("Im Feeling lucky link is not displayed", driver.findElement(By.xpath(xpathToImFeelingLuckyButton)).isDisplayed());
        Assert.assertTrue("About Link is not displayed", driver.findElement(By.xpath(xpathToAboutLink)).isDisplayed());
        Assert.assertTrue("Gmail Link is not displayed", driver.findElement(By.xpath(xpathToGmailLink)).isDisplayed());
        Assert.assertTrue("Image Link is not displayed", driver.findElement(By.xpath(xpathToImagesLink)).isDisplayed());
    }

    @Test
    public void validateSearchResultPageElements() {
        Assert.assertFalse("Image Link is displayed", driver.findElement(By.xpath(xpathToImagesLink)).isDisplayed());
        Assert.assertFalse("Gmail Link is displayed", driver.findElement(By.xpath(xpathToGmailLink)).isDisplayed());
        Assert.assertTrue("Search Results are not displayed", driver.findElement(By.xpath(xpathToSearchResult)).isDisplayed());
    }
}

This is the Search Result Page Class file

public class SearchResultPage {
     public SearchResultPage() {
        isLogoDisplayed();
        isPagenationDisplayed();
        isTitleCorrect();
        isSearchButtonDisplayed();
    }

    private void isLogoDisplayed() {
        System.out.println("Logo displayed..??");
    }

    private void isSearchButtonDisplayed() {
        System.out.println("Search Button displayed..??");
    }

    private void isPagenationDisplayed() {
        System.out.println("Pagination displayed..??");
    }

    private void isTitleCorrect() {
        System.out.println("Title Correct..??");
    }

    public  void isSearchResultDisplayed() {
        System.out.println("This is where I can test some other test");
    }

}

This is from where we invoke the tests.

import org.junit.Test;

public class SearchResultPageTest {
    @Test
    public  void validateSearchResultPage() {
        // By creating the object of the SearchResultPage() class, the validations are done
        new SearchResultPage();
    }

    @Test
    public void validateSomethingSpecial() {
        SearchResultPage searchResultPage = new SearchResultPage();
        searchResultPage.isSearchResultDisplayed();
    }
}



Wednesday, 21 October 2015

Page Object Model

Hello All,

In this blog post, let us discuss about the Page Object Model structure in Automation Testing.
Page Object Model (POM) is a very powerful way of testing the web applications.

In this POM, testing the web pages is very simple and it is an organized way. This helps to minimize the number of function calls and optimizes tests.

To illustrate the difference, lets take two examples.

Example to validate the webpage normally

If we are not using Page Object Model, we have to validate the elements separately.

See picture below


Example with POM way of validating pages

Using POM, we need not explicitly validate the page elements separately.
See Picture below




Learn more on how to create a POM with examples here

Tuesday, 13 October 2015

BDD configuration with Selenium Automation

Cucumber – JVM
1.       Introduction to BDD
2.       Introduction to Cucumber
a.       Life without Cucumber
b.      Need of Cucumber
c.       Advantages of Cucumber
3.       Understanding Maven Project
a.       Installation
b.      Setting environment variables
c.       POM
d.      Project Structure
4.       Examples using Maven
a.       Configuring dependencies
b.      Configuring Profiles
5.       Examples with Selenium
6.       Configuring the Cucumber Jars using Maven
7.       Understanding the Cucumber Approach
8.       Different Keywords used in Cucumber
a.       Feature
b.      Scenario
c.       Scenario Outline
d.      Examples
e.      GIVEN
f.        WHEN
g.       THEN
h.      AND
i.         BUT
9.       Regular Expressions in Java
10.   Learning to write Regex
11.   Passing values to Step-definitions in different formats
a.       String
b.      Boolean
c.       Numbers
d.      List
e.      Maps
f.        @Format…
12.   Results/Reports