Dependency Injection with Selenium and Spring Boot

Hello guys,

Today I am going to share something that I learned recently. I am aware that so many people probably have been using this a long time ago, but I have moved away from java and Selenium quite some time ago and I recently got back into it.

So here is a boilerplate with an automated test project using Dependency Injection of Spring Boot with Selenium, Gradle, and Cucumber.

Feel free to contribute or give any feedback !!

Github project: https://github.com/rafaelaazevedo/Scrux

Stale Element when using PageFactory – Selenium

Photo by luis gomes on Pexels.com

Hello guys,

The first post of the year will be a quick one. Took me a while to figure out since it has been ages I coded in Selenium/Java and used PageFactory (which I thought was deprecated, but it is just deprecated in C#)

If you ever come across an error like this when using PageFactory:

stale element reference: element is not attached to the page document

PageFactory initializes the elements the first time you run the automation and when the page changes (which happens on Angular and React pages) Selenium loses the reference to that element and needs to find it again with the new DOM.

You can do something like this:

protected void clickElement(WebElement element) {
   try {
      webDriverUtils.waitForElementToBePresent(element);
      element.click();
   } catch (StaleElementReferenceException e) {
       PageFactory.initElements(driver, this);
   }

Open different browsers with C# and Selenium

Hey guys, I am going to post some snippets to run a test in different browsers with C# and selenium.

Import:

using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.IE;
using OpenQA.Selenium.PhantomJS;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NUnit.Framework;
using OpenQA.Selenium.Support.PageObjects;
using Assert = NUnit.Framework.Assert;

 

Driver Utils class: 

Just the beginning of the class declaring the WebDriver and the TxtSearch field, which will be used for all the below functions to open a specific browser.

namespace Helpers
{
 [TestClass]
 public class DriverUtils
 {
 IWebDriver webDriver;

 //Declaring search element
 [FindsBy(How = How.Name, Using = "q")]
 public IWebElement TxtSearch { get; set; }

 

Open Chrome:

 [Test]
 public void Chrome_Browser()
 {
 webDriver = new ChromeDriver();
 AssertSearchElement();
 }

 

Open Chrome Mobile Emulator:

 [Test]
 public void Chrome_Mobile_Emulator_Browser()
 {
 ChromeOptions chromeCapabilities = new ChromeOptions();
 chromeCapabilities.EnableMobileEmulation("Google Nexus 5");
 webDriver = new ChromeDriver(chromeCapabilities);
 AssertSearchElement();
 }

 

Open Chrome Capabilities starts Maximized:

 [Test]
 public void Chrome_Capabiblities_Browser()
 {
 ChromeOptions chromeCapabilities = new ChromeOptions();
 chromeCapabilities.AddArgument("start-maximized");
 webDriver = new ChromeDriver(chromeCapabilities);
 AssertSearchElement();
}

 

Open Firefox:

[Test]
 public void Firefox_Browser()
 {
 webDriver = new FirefoxDriver();
 AssertSearchElement();
}

 

Open Firefox with Profile:

[Test]
 public void Firefox_Profile_Browser()
 {
 var profile = new FirefoxProfile();
 profile.SetPreference("browser.startup.homepage", 
"https://www.azevedorafaela.wordpress.com/");
 webDriver = new FirefoxDriver(profile);
 AssertSearchElement();
}

 

Open PhantomJS:

[Test]
 public void PhantomJS_Browser()
 {
 webDriver = new PhantomJSDriver();
 AssertSearchElement();
}

 

Open PhantomJS with Capabilities:

[Test]
 public void PhantomJS_Capabilities_Browser()
 {
 var options = new PhantomJSOptions();
 options.AddAdditionalCapability("phantomjs.page.settings.userAgent", 
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) 
Chrome/40.0.2214.94 Safari/537.36");
 webDriver = new PhantomJSDriver(options);
 AssertSearchElement();
}

 

Open Internet Explorer:

 [Test]
 public void IE_Browser()
 {
 webDriver = new InternetExplorerDriver();
 AssertSearchElement();
}

 

Open Internet Explorer with Options:

[Test]
 public void IE_Options_Browser()
 {
 var options = new InternetExplorerOptions
 {
 IgnoreZoomLevel = true 
 };

 webDriver = new InternetExplorerDriver(options);
 AssertSearchElement();
}

 

Assert Search Element is Displayed:

public void AssertSearchElement()
 {
 webDriver.Navigate().GoToUrl("https://www.google.com");

 PageFactory.InitElements(webDriver, this);
 Assert.IsTrue(TxtSearch.Displayed);
}

 

Close/Quit Browser and driver function:

[TearDown]
public void CloseDriver(IWebDriver driver)
  {
  driver.Close();
  driver.Quit();
  }
 }
}

 

See you again in the end of this week, hopefully I will have the complete flow for a BDD scenario with C# and Selenium.

 

Code example to catch url, Status code and time to load an url

Hi guys, today I will post a simple project that I did just to catch some information with Selenium and Java. So, I have a spreadsheet with some urls in the first column and when I run the project, it is being recorded the status code of the urls and how long is lasting to load this page in the following columns.

It is very simples. I know that there are many ways to do that and you don’t need to use selenium because will take more time to render the page and everything, but maybe someone is needing something similar. So, now the code and in the bottom the link to my project.

  • OPEN URL – Open the URL and write the StatusCode and the time to load the page in the following columns:
import jxl.read.biff.BiffException;
import org.openqa.selenium.WebDriver;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.openqa.selenium.By;

public class OpenUrl {

    OpenDataBase opendatabase = new OpenDataBase();
    FileOutputStream fOut = null;

    public void OpenURL(WebDriver driver) throws BiffException, Exception {
        String tablename = ("tb");
        opendatabase.Open(tablename);
        File file = new File("BD.xls");
        int result = 0;
        String STR = "CRI -";
        int ARQ = 1;
        int WARNING = 2;
        int CRITICAL = 3;

        Workbook wb = new HSSFWorkbook(new FileInputStream(file.
getCanonicalPath()));

        for (int i = 0; i < opendatabase.sheet.getRows(); i++) {

            String url = opendatabase.sheet.getCell(0, i).getContents();

            double start = System.currentTimeMillis();
            driver.manage().window().maximize();
            driver.get(url);
            double finish = System.currentTimeMillis();
            double totalTime = finish - start;
            double totalTimeSec = totalTime / 1000;

            try {
                driver.findElement(By.xpath("/html/body/div/span[2]/ul/li/a")
).click();
            } catch (Exception e) {
                driver.findElement(By.xpath("/html/body/div/span/ul/li/a")
).click();
            }

            String titlepage = driver.getTitle().replace(" ", "");

            FileWriter fw = new FileWriter(titlepage + ".txt");
            int statusCode = Statuscode(driver.getCurrentUrl(), driver);
            String line = url + "," + totalTimeSec + "," + statusCode;

            fw.write(line);
            fw.close();


        }


    }

    public int Statuscode(String URLName, WebDriver driver) {
        try {
            int statuscode = Integer.parseInt(driver.findElement(By.xpath
("/html/body/div/span/span/pre[2]")).getText().substring(9, 12));
            return statuscode;
        } catch (Exception e) {
            e.printStackTrace();
            return 1;
        }
    }
}
  • OPEN DATABASE CODE – Read the columns in the Excel Spreadsheet:
import java.io.File;
import java.io.IOException;
import jxl.Sheet;
import jxl.Workbook;
import jxl.WorkbookSettings;
import jxl.read.biff.BiffException;

public class OpenDataBase{

    Sheet sheet;
    Workbook bdurl;
      
    public Sheet Open(String tablename) throws BiffException, IOException, 
Exception { 

        File file = new File("BD.xls");
            WorkbookSettings ws = new WorkbookSettings();
            ws.setEncoding("Cp1252");
            
            bdurl = Workbook.getWorkbook(new File(file.getCanonicalPath()), 
ws);             
            
            sheet = bdurl.getSheet(tablename);
            return sheet;
        }

    public void Close(Workbook bdurl) throws BiffException, IOException, 
Exception {

        bdurl.close();
    }
}

 

  • MAIN CLASS – statusCode:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.firefox.internal.ProfilesIni;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;

public class statusCode {

    public static void main(String[] args) throws Exception {
        ProfilesIni profilesIni = new ProfilesIni();
        FirefoxProfile profile = profilesIni.getProfile("default");
        WebDriver driver = new FirefoxDriver(profile);

        DesiredCapabilities capabilities = new DesiredCapabilities();
        capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
        
        profile.setPreference("browser.ssl_override_behavior", 1);
        profile.setPreference("network.proxy.type", 0);
        profile.setAcceptUntrustedCertificates(true);
        profile.setAssumeUntrustedCertificateIssuer(false);

        driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);

        OpenUrl Openurl = new OpenUrl();
        Openurl.OpenURL(driver);
        
        driver.close();
        driver.quit();
    }
}

Thanks guys ! See you next week, if you have any questions, suggestion please feel free to comment below.

Sourcehttps://github.com/rafaelaazevedo/statuscode_nfe

Running Selenium Headless Firefox in UBUNTU

If you want run your tests with Selenium without open the browser Firefox, I will write how you can do this:

Verify if you have the last version of Firefox.

1 – Install Firefox headless in Ubuntu

  • Open the file: /etc/apt/sources.list and add the line:
    ppa:mozillateam/firefox-stable
  • Open the terminal and run the commands:
     sudo apt-get update
     sudo apt-get install firefox

 

2 – Install Xvfb – the X Virtual FrameBuffer. This piece of software emulates the framebuffer using virtual memory which lets you run X-Server in machines with no display devices. This service is required to make browsers run normally by making them believe there is a display available.

  • Open the terminal and run the command:
    sudo apt-get install xvfb
  • Lets run the xvfb service in a display number which is less likely to clash even if you add a display at later stage. For this example, we will assume a display, 5. The parameter -ac makes xvfb run with access control off. The server should be running now.sudo Xvfb :5 -ac

 

3 – Start browser headlessly in Ubuntu

  • Run the command:
    export DISPLAY=:5
    firefox

If there was no error on the terminal, then you have successfully running firefox headlessly in Ubuntu. The command should keep running until you kill the process by pressing ctrl+ C or similar. There wont be any output. Now, you can run selenium server as you will run in your local machine.

 

Fonthttp://www.installationpage.com/selenium/how-to-run-selenium-headless-firefox-in-ubuntu/

 

 

 

Testing Ajax application with Selenium

Ajax, an acronym for Asynchronous JavaScript and XML, is a web development technique for creating interactive and more responsive web applications. The Ajax application works more like a desktop application, meaning that user’s request will not cause an entire page to reload every time, the web browser makes an asynchronous call to the web server to obtain the required data and update only specific parts of the current web page. As result the user gets more interactive, speedy, and usable web pages, but testing AJAX with Selenium will be challenging.

Selenium’s ‘assert’ and ‘verify’ commands might occasionally fail thanks to the asynchronous nature of the Ajax. It may happened that the result doesn’t come back from the server immediately and while ‘assert’ and ‘verify’ commands already trying to verify a new value immediately.

Not experienced testers would recommend to add a ‘pause’ command for a few seconds before the verification. The ‘pause’ suggestion may work in certain cases, because Ajax call may be not completed after pausing for a specific time due to slow machines or network. If the tester set the long pause time it will make the test unacceptably slow and drastically increase testing time.

In this type of tests you should use waitForCondition function in Selenium for Ajax testing. The waitForCondition command evaluates a JavaScript snippet repeatedly, until the snippet returns true. As soon as Selenium detects that the condition returns true, it will stop waiting and Ajax testing will resume.

It is important to note that the selenium in selenium.waitForCondition is a Java object in your test code and the selenium in selenium.browserbot is a javascript object running in the web browser.

Examples:

selenium.waitForCondition("selenium.browserbot.getCurrentWindow().loading == false", "20000");

> Condition

> Timeout miliseconds

If you are using AJAX you might find there is an AJAX object on your application. In it will be a activeRequestCount. When the AJAX.activeRequestCount goes to zero, all the AJAX calls are done. So you can wait for an AJAX call to complete with:

selenium.waitForCondition("selenium.browserbot.getCurrentWindow().AJAX.activeRequestCount == 0", "30000");

Thank you 🙂

 

Fontshttp://www.seleniumguide.com/p/testing-ajax-with-selenium.html

http://darrellgrainger.blogspot.co.uk/2010/03/selenium-rc-java-waitforcondition.html

Behat, Mink and Selenium

Hello guys !

I will explain a simple tutorial of “How can you use BDD with Selenium and PHP.”

– First thing you have to install Behat:

– Install Composer

– Create a composer.json file in your root directory

1
2
3
4
5
6
7
8
9
{
“require”: {
“behat/behat”: “2.4.*@stable”,
“behat/mink”: “1.5.*@stable”,
“behat/mink-goutte-driver”: “*”,
“behat/mink-extension”: “*”,
“behat/mink-selenium2-driver”: “*”
}
}

 

– Run composer install

– Create a behat.yml file

 

1
2
3
4
5
6
7
8
default:
paths:
features: features
bootstrap: %behat.paths.features%/bootstrap
extensions:
Behat\MinkExtension\Extension:
goutte: ~
selenium2: ~

 

– Initialize your Behat project with vendor/bin/behat –init. Note: bin directories are configurable in composer.json. If your composer file has a bin directory, use that path instead of vendor/bin.

– Create a feature file, e.g. test.feature
1
2
3
4
5
6
7
8
9
10
Feature: Drupal.org search
In order to find modules on Drupal.org
As a Drupal user
I need to be able to use Drupal.org search
@javascript
Scenario: Searching for “behat”
Given I go to “http://drupal.org
When I search for “behat
Then I should see “Behat Drupal Extension

 

– Edit FeatureContext.php to extend from MinkContext. Note: You will need to add the use statement, use Behat\MinkExtension\Context\MinkContext. Run vendor/bin/behat

– Second Step: Adding Selenium as an optional driver

– Download Selenium Server

– Run java -jar /path/to/selenium-server-standalone-2.37.0.jar

– Add selenium2: ~ to your behat.yml

– Add a @javascript tag above your scenario

– Run vendor/bin/behat

– Third Step: Adding new step definitions

– Add the step you want to create in your scenario, e.g.

– When I search for “behat” Run vendor/bin/behat

– Copy the step definition template to FeatureContext.php and replace the PendingException with your code.

1
2
3
4
5
6
7
8
/**
* @When /^I search for “([^”]*)”$/
*/
public function iSearchFor($arg1)
{
$this->fillField(‘Search Drupal.org’, $arg1);
$this->pressButton(‘Search’);
}

 

Resources: http://lin-clark.com/blog/2013/11/26/quickstart-testing-with-behat-mink-selenium/

Selenium First Steps

Hello guys !!

I have a friend that asked to me somethings to start in Selenium’s world. For this reason I will write today about first steps to automate in Selenium.

In this example, we will open in the Chrome browser. Install the Chrome in your Operational System and after that, you have to download the driver too.

The link to download the driver is: http://chromedriver.storage.googleapis.com/index.html

Now, you have to download the WebDriver’s lib. You can download in this link: http://docs.seleniumhq.org/download/

Import the lib in your Java project. This is how the structure will looks like. Pay attention on the folder of Libraries in this picture below.

structure

This is the package and the libs imported to use in our automation:

libs_import

This is the code to use the chrome’s driver. You have to put this, because the Chrome won’t open without the driver and this line. If you are using Windows, you have to download the .exe file. Each OS that you use, you have a specific file to download. After write this line, you will instantiate the ChromeDriver and write the command below, to open a site in Chrome.

comands-initial

You can find an element of different ways. You can use the id, the classname, tagname, etc… Xpath is the last option that you have to use, because there is a lot of problems when you have to use it in mutiple browsers. So, you can look all the possibilities in the picture below:

how-find-element-and-use

 

 

This is the correct way to wait some element to load on your page. You have to put this after load a new page, or click on a new function. It is better put this expected conditions to wait a element than put a time to wait, because unfortunately we depend a lot of environment and browser.

how-wait-until

You can use these commands to click and write something in specific field, respectively. You can instantiate the element and you will use only one time to search it. After that, you can use the instance to click, send words and others actions in the element without looking it again.

commands

This is the command to close the browse, to close the driver, respectively, and finish your automation. After this, you can’t use the driver anymore, unless you instantiate again another WebDriver.

how-close-browser

This is the final code ! Maybe your code will looks like with mine. Afterward, just put to run and see the automation !

code-complete

Bye guys !!

Open saved profiles in Firefox – Selenium (WebDriver)

Hello, I will put the code that you need for open some saved profile in Firefox with Selenium.

ProfilesIni profilesIni = new ProfilesIni();
FirefoxProfile profile = profilesIni.getProfile(“default“); //This is the name of profile, you can find this in the folder of firefox profiles.
WebDriver driver = new FirefoxDriver(profile);
 
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true); // Only necessary if you have invalid certificates in the page
                
profile.setPreference(“network.proxy.type”, 0); // open without proxy
profile.setAcceptUntrustedCertificates(true); // Only necessary if you have invalid certificates in the page
profile.setAssumeUntrustedCertificateIssuer(false); // Only necessary if you have invalid certificates in the page
 
I use this way for open a saved profile that contains a personal certificate. I needed open 
a page with this certificate installed.
 
Bye bye 🙂