Selenium

Selenium is a great tool for web testing. It uses a browser to run verifications and it can handle all the popular browsers, such as Firefox, Safari, and Chrome. It also supports headless browsers to test web pages with much greater speed and less resources consumption.

There is a SeleniumIDE plugin that can be used to create tests by recording actions performed by the user. Currently, it is only supported by Firefox. Sadly, even though tests generated this way provide very fast results, they tend to be very brittle and cause problems in the long run, especially when some part of a page changes. For this reason, we'll stick with the code written without the help from that plugin.

The simplest way to execute Selenium is to run it through JUnitRunner.
All Selenium tests start by initializing WebDriver, the class used for communication with browsers:

  1. Let's start by adding the Gradle dependency:
dependencies { 
  testCompile 'org.seleniumhq.selenium:selenium-java:2.45.0' 
} 
  1. As an example, we'll create a test that searches Wikipedia. We'll use a Firefox driver as our browser of choice:
WebDriver driver = new FirefoxDriver(); 

WebDriver is an interface that can be instantiated with one of the many drivers provided by Selenium:

  1. To open a URL, the instruction would be the following:
driver.get("http://en.wikipedia.org/wiki/Main_Page");
  1. Once the page is opened, we can search for an input element by its name and then type some text:
WebElement query = driver.findElement(By.name("search")); 
query.sendKeys("Test-driven development"); 
  1. Once we type our search query, we should find and click the Go button:
WebElement goButton = driver.findElement(By.name("go")); 
goButton.click();
  1. Once we reach our destination, it is time to validate that, in this case, the page title is correct:
assertThat(driver.getTitle(), 
startsWith("Test-driven development"));
  1. Finally, the driver should be closed once we're finished using it:
driver.quit(); 

That's it. We have a small but valuable test that verifies a single use case. While
there is much more to be said about Selenium, hopefully, this has provided you
with enough information to realize the potential behind it.


Visit http://www.seleniumhq.org/ for further information and more complex uses of WebDriver.

The complete source code can be found in the SeleniumTest class in the https://bitbucket.org/vfarcic/tdd-java-ch02-example-web repository.

While Selenium is the most commonly used framework to work with browsers, it is still very low-level and requires a lot of tweaking. Selenide was born out of the idea that Selenium would be much more useful if there was a higher-level library that could implement some of the common patterns and solve often-repeated needs.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.17.154