Monday, July 30, 2018

Configure Cucumber using Gradle in Eclipse

To configure Cucumber using Gradle in Ecilpse, you may follow the same steps in Configure Selenium WebDriver using Gradle in Eclipse. The only thing you need to do is to add cucumber dependency in build.gradle file.

To get the latest cucumber dependency, you may check the Cucumber website here or search.maven.org by searching 'cucumber-java'. The latest version is 3.0.2.

And copy cucumber gradle config to build.gradle file.

dependencies {
    // testCompile 'io.cucumber:cucumber-java8:3.0.2'
    testCompile 'io.cucumber:cucumber-java:3.0.2'
    testCompile 'io.cucumber:cucumber-junit:3.0.2'
}

Wednesday, July 25, 2018

Testing Report using Gradle

After we execute all the test cases using Gradle "test" task, it will generate HTML reports for us, it shows how many tests failed and how many tests passed.

There are two ways to execute the Gradle "test" task.

1) Run Gradle test in eclipse

After finish running all test cases, it looks like this,


2) Execute "gradle test" in command line under the project directory

3) Open the report HTML file in the browser

Tuesday, July 24, 2018

Capture Screenshot when Test Failed

Capture screenshot if the test case failed is an essential feature for investigating the defects. Selenium WebDriver implemented TakesScreenshot interface which is easy to take a screenshot from web browser screen. Here is an example:

public class Screenshot {

    public static void takeScreenshot(String screenshotPath, WebDriver driver) {
        try {
            File screenshotFile =
                  ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
            FileUtils.copyFile(screenshotFile, new File(screenshotPath));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void takeScreenshot(WebDriver driver, String method) {
        String screenshotName = DateUtils.formatDate(new Date(), "yyyyMMddHHmmss_")
                   + method + ".jpg";
        String dateString = DateUtils.formatDate(new Date(), "yyyyMMdd");
        File dir = new File("screenshots/" + dateString);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        String screenshotPath = dir.getAbsolutePath() + "/" + screenshotName;
        takeScreenshot(screenshotPath, driver);
    }

}

JUnit Test Case:

@RunWith(SimpleRunner.class)
public class ScreenshotTest {

    public static WebDriver driver;

    @BeforeClass
    public static void setUpBeforeClass() {
        driver = new ChromeDriver();
    }

    @AfterClass
    public static void tearDownAfterClass() {
        driver.quit();
    }

    @Test
    public void testPercentageCalculation() {
        // open http://www.percentagecalculator.co/ web site
        driver.get("http://www.percentagecalculator.co/");
        // find A element and type 10
        driver.findElement(By.id("A")).sendKeys("10");
        // find B element and type 100
        driver.findElement(By.id("B")).sendKeys("100");
        // find C element
        WebElement c = driver.findElement(By.id("C"));
        // validate result
        assertEquals("11", c.getAttribute("value"));
    }

}

JUnit Runner:

public class SimpleRunner extends BlockJUnit4ClassRunner {

    public SimpleRunner(Class<?> clazz) throws InitializationError {
        super(clazz);
    }

    @Override
    public void run(RunNotifier notifier) {
        notifier.addListener(new JUnitExecutionListener());
        notifier.fireTestRunStarted(getDescription());
        super.run(notifier);
    }

}

RunListener:

public class JUnitExecutionListener extends RunListener {

    public void testRunStarted(Description description) throws Exception {
    }

    public void testRunFinished(Result result) throws Exception {
    }

    public void testStarted(Description description) throws Exception {
    }

    public void testFinished(Description description) throws Exception {
    }

    public void testFailure(Failure failure) throws Exception {
        Screenshot.takeScreenshot(ScreenshotTest.driver,
            failure.getDescription().getMethodName());
    }

    public void testAssumptionFailure(Failure failure) {
        Screenshot.takeScreenshot(ScreenshotTest.driver,
            failure.getDescription().getMethodName());
    }

    public void testIgnored(Description description) throws Exception {
    }

}

Monday, July 23, 2018

Setup Selenium Grid

With Selenium Grid you can create a simple infrastructure of various browsers on different operating systems to not only distribute test load but also give you a diversity of browsers to work with.

 1) Download Selenium Standalone Server
     You man download Selenium standalone server jar file from here. And put the jar file in your disk folder.

2) Start Hub Machine
     Open command line window and navigate to the folder of jar file and run the command below.
     java -jar selenium-server-standalone-3.13.0.jar -role hub
     The hub will be running on default port 4444, you may access the link http://localhost:4444 to check the hub status.

3) Start Node Machine
     Navigate to the folder of jar file on the node machine in command line window, and run the command below.
     java -jar selenium-server-standalone-3.3.1.jar -role node -hub   
            http://<hub>:4444/grid/register -port 5555
     It will start a node on port 5555 and register on the hub. Then you may find it on the hub machine status page.

4) Connect to Remote Driver
     DesiredCapabilities cap = DesiredCapabilities.firefox();
     WebDriver driver = new RemoteWebDriver(new URL("http://<hub>:4444/wd/hub"), cap);

Here is an example test case.

package me.simplejavautomation;

import static org.junit.Assert.assertEquals;

import java.net.URL;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.PageFactory;

import me.simplejavautomation.pages.PercentageCalculatorPage;

public class GridTest {

    private WebDriver driver;

    @Before
    public void setUp() throws Exception {
        String hub = "http://192.168.1.61:4444/wd/hub";
        DesiredCapabilities cap = DesiredCapabilities.firefox();
        driver = new RemoteWebDriver(new URL(hub), cap);
    }

    @After
    public void tearDown() {
        driver.quit();
    }

    @Test
    public void testPercentageCalculation() {
        // open http://www.percentagecalculator.co/ web site
        driver.get("http://www.percentagecalculator.co/");

        PercentageCalculatorPage pageObject = PageFactory.initElements(driver,
             PercentageCalculatorPage.class);
        pageObject.getA().sendKeys("10");
        pageObject.getB().sendKeys("100");

        assertEquals("10", pageObject.getC().getAttribute("value"));
    }

}

Friday, July 20, 2018

PageObejctModel in Selenium WebDriver

Page object model is a wonderful design pattern to abstract out Web Page elements and its actions from actual tests. We can use this way to build a test framework of the project and focus on business only in all the test cases.

Here is a demo for page object model.


package me.simplejavautomation.pages;

import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;

public class PercentageCalculatorPage {

    @FindBy(id = "A")
    private WebElement a;

    @FindBy(id = "B")
    private WebElement b;

    @FindBy(id = "C")
    private WebElement c;

    public WebElement getA() {
        return a;
    }

    public void setA(WebElement a) {
        this.a = a;
    }

    public WebElement getB() {
        return b;
    }

    public void setB(WebElement b) {
        this.b = b;
    }

    public WebElement getC() {
        return c;
    }

    public void setC(WebElement c) {
        this.c = c;
    }

}

package me.simplejavautomation;

import static org.junit.Assert.assertEquals;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.PageFactory;

import me.simplejavautomation.pages.PercentageCalculatorPage;

public class PageObjectTest {

    private WebDriver driver;

    @Before
    public void setUp() {
        driver = new ChromeDriver();
    }

    @After
    public void tearDown() {
        driver.quit();
    }

    @Test
    public void testPercentageCalculation() {
        // open http://www.percentagecalculator.co/ web site
        driver.get("http://www.percentagecalculator.co/");

        PercentageCalculatorPage pageObject = PageFactory
            .initElements(driver, PercentageCalculatorPage.class);
        pageObject.getA().sendKeys("10");
        pageObject.getB().sendKeys("100");

        assertEquals("10", pageObject.getC().getAttribute("value"));
    }

}

Thursday, July 19, 2018

Execute Javascript in Selenium WebDriver

To execute Javascript using Selenium WebDriver, we can use JavascriptExecutor interface to implement it. There are two methods in JavascriptExecutor interface.

  • executeScript(String, Object...)
  • executeAsyncScript(String, Object...)

Here is a simple test,


    @Test
    public void testJavascript() throws InterruptedException {
        // wait 10 seconds if web element is not present
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        JavascriptExecutor jsExecutor = (JavascriptExecutor) driver;
        jsExecutor.executeScript("alert('hello world');");
        TimeUnit.SECONDS.sleep(4);
        driver.switchTo().alert().accept();

        WebElement continents = (WebElement) jsExecutor
            .executeScript("return document.getElementById('continents')");
        assertNotNull(continents);

        String selectedContinent = jsExecutor
             .executeScript("return document.getElementById('continents').value")
             .toString();
        assertEquals("Asia", selectedContinent);
    }

Tuesday, July 17, 2018

Actions on WebElement in Selenium WebDriver

Actions is an interaction generator in Selenium WebDriver which allow us to operate complicated user interactions on web pages.
You can perform actions such as drag and drop, move, click, double-click, and tick and so on.

Here is an example of a demo of drag and drop, and move on a menu.

package me.simplejavautomation;

import static org.junit.Assert.assertEquals;

import java.util.concurrent.TimeUnit;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;

public class ActionsApiTest {

    private WebDriver driver;
    private String url;

    @Before
    public void setUp() {
        driver = new ChromeDriver();
        url = "http://simplejavautomation.blogspot.com/2018/07/demo-page-for-actions-in-selenium.html";
        // go to the demo page
        driver.get(url);
        // maximize the browser window
        driver.manage().window().maximize();
    }

    @After
    public void tearDown() {
        driver.quit();
    }

    @Test
    public void testDragAndDrop() throws InterruptedException {
        // wait 10 seconds if web element is not present
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

        WebElement from = driver.findElement(By.id("draggable"));
        WebElement to = driver.findElement(By.id("droppable"));

        Actions builder = new Actions(driver);
        // builder.clickAndHold(from).release(to).build().perform();
        builder.dragAndDrop(from, to).build().perform();
    }

    @Test
    public void testMenuClick() throws InterruptedException {
        // wait 10 seconds if web element is not present
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

        WebElement automation = driver.findElement(By.id("automation"));

        Actions builder = new Actions(driver);
        builder.moveToElement(automation).build().perform();

        driver.findElement(By.id("selenium")).click();

        assertEquals("Selenium",
             driver.findElement(By.id("selectedText")).getText());
    }

}