Selenium WebDriver - Running test on Safari Browser using Java
Last Updated :
06 Aug, 2024
Selenium WebDriver is a powerful tool for automating web application testing. It supports multiple browsers, including Safari. In this guide, we'll walk through the steps to set up and run tests on Safari using Java. This includes setting up the environment, writing basic tests, handling dynamic elements, and integrating with CI/CD pipelines.
Selenium WebDriver
II. Setting Up the Environment
A. Dependencies
To get started, you need the following dependencies:
- Java Development Kit (JDK)
- Maven or Gradle for dependency Management
- Selenium Java bindings
- SafariDriver (built-in with macOS)
Add the following dependencies to your pom.xml (if using Maven):
XML
<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.4.0</version>
<scope>test</scope>
</dependency>
</dependencies>
B. Downloading and Configuring SafariDriver
SafariDriver comes pre-installed with Safari on macOS, so no additional download is needed. Ensure the 'Allow Remote Automation' option is enabled in Safari’s Develop menu:
- Open Safari.
- Go to Safari -> Preferences -> Advanced.
- Check Show Develop menu in menu bar.
- In the Develop menu, check Allow Remote Automation.
C. Project Structure and Test Framework
Organize your project with the following structure:
/project-root
/src
/main
/test
/java
/com
/example
/tests
BaseTest.java
SafariTest.java
pom.xml
Use a test framework like TestNG or JUnit. Below is an example pom.xml setup for TestNG:
XML
<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.4.0</version>
<scope>test</scope>
</dependency>
</dependencies>
III. Writing Basic Safari Tests with Java
A. Launching Safari Browser
Create a base test class to initialize the WebDriver:
Safari Browser
Java
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.safari.SafariDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
public class BaseTest {
protected WebDriver driver;
@BeforeMethod
public void setUp() {
driver = new SafariDriver();
driver.manage().window().maximize();
}
@AfterMethod
public void tearDown() {
if (driver != null) {
driver.quit();
}
}
}
B. Navigating Websites and Interacting with Elements
Navigating Websites
Example test for navigating and interacting:
Java
import org.testng.Assert;
import org.testng.annotations.Test;
public class SafariTest extends BaseTest {
@Test
public void testNavigateAndInteract() {
driver.get("https://www.example.com");
String title = driver.getTitle();
Assert.assertEquals(title, "Example Domain");
}
}
C. Assertions and Verifications
Using TestNG assertions:
Java
import org.testng.Assert;
@Test
public void testTitle() {
driver.get("https://www.example.com");
String title = driver.getTitle();
Assert.assertEquals(title, "Example Domain");
}
D. Taking Screenshots and Debugging
Taking Screenshot
Java
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.testng.annotations.Test;
import java.io.File;
import java.io.IOException;
@Test
public void testScreenshot() {
driver.get("https://www.example.com");
File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(screenshot, new File("screenshot.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
E. Handling Dynamic Elements and Ajax
Use WebDriverWait for dynamic elements:
Java
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.Test;
@Test
public void testDynamicElement() {
driver.get("https://www.example.com");
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement dynamicElement = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("dynamicElementId")));
Assert.assertTrue(dynamicElement.isDisplayed());
}
F. Handling Alerts and Popups
Java
import org.openqa.selenium.Alert;
@Test
public void testAlertHandling() {
driver.get("https://www.example.com/alert");
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
Assert.assertEquals(alertText, "Expected Alert Text");
alert.accept();
}
G. File Uploads and Downloads:
Java
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
@Test
public void testFileUpload() {
driver.get("https://www.example.com/upload");
WebElement uploadElement = driver.findElement(By.id("upload"));
uploadElement.sendKeys("/path/to/file.txt");
}
H. Parallel Testing and Grid
Set up parallel testing in TestNG:
XML
<suite name="Suite" parallel="tests" thread-count="4">
<test name="Test1">
<classes>
<class name="com.example.tests.SafariTest"/>
</classes>
</test>
<test name="Test2">
<classes>
<class name="com.example.tests.AnotherTest"/>
</classes>
</test>
</suite>
I. Page Object Model (POM)
Create a Page Object:
Java
package com.example.pages;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class LoginPage {
private WebDriver driver;
private By usernameField = By.id("username");
private By passwordField = By.id("password");
private By loginButton = By.id("login");
public LoginPage(WebDriver driver) {
this.driver = driver;
}
public void enterUsername(String username) {
driver.findElement(usernameField).sendKeys(username);
}
public void enterPassword(String password) {
driver.findElement(passwordField).sendKeys(password);
}
public void clickLogin() {
driver.findElement(loginButton).click();
}
}
J. Data-Driven Testing with Excel/CSV
Using Apache POI for Excel:
Java
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.io.FileInputStream;
import java.io.IOException;
public class DataDrivenTest {
@DataProvider(name = "excelData")
public Object[][] readExcel() throws IOException {
FileInputStream file = new FileInputStream("data.xlsx");
Workbook workbook = new XSSFWorkbook(file);
Sheet sheet = workbook.getSheetAt(0);
int rowCount = sheet.getPhysicalNumberOfRows();
Object[][] data = new Object[rowCount][2];
for (int i = 0; i < rowCount; i++) {
Row row = sheet.getRow(i);
data[i][0] = row.getCell(0).getStringCellValue();
data[i][1] = row.getCell(1).getStringCellValue();
}
return data;
}
@Test(dataProvider = "excelData")
public void testWithExcelData(String username, String password) {
// Use the username and password in your test
}
}
K. Reporting and Continuous Integration
Generating test reports (HTML, JUnit XML) with TestNG:
XML
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>testng.xml</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
</plugins>
</build>
IV. Generating Test Reports (HTML, JUnit XML)
TestNG generates default reports in the target/surefire-reports directory. For custom reports, use listeners or report generators like ExtentReports.
V. Integrating Tests with CI/CD Pipelines (Jenkins, Azure DevOps)
Jenkins
- Install the TestNG plugin.
- Configure a Jenkins job to run your Maven project.
- Add a post-build action to publish TestNG reports.
Azure DevOps
- Create a pipeline with a Maven task.
Azure DevOps - Configure the task to run your tests and publish test results.
Conclusion
Running Selenium tests on Safari using Java involves setting up the environment, writing robust test cases, handling various web elements, and integrating with CI/CD pipelines. By following this guide, you should be able to create a comprehensive testing setup for Safari.
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
What is Vacuum Circuit Breaker? A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac
13 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
CTE in SQL In SQL, a Common Table Expression (CTE) is an essential tool for simplifying complex queries and making them more readable. By defining temporary result sets that can be referenced multiple times, a CTE in SQL allows developers to break down complicated logic into manageable parts. CTEs help with hi
6 min read
Python Variables In Python, variables are used to store data that can be referenced and manipulated during program execution. A variable is essentially a name that is assigned to a value. Unlike many other programming languages, Python variables do not require explicit declaration of type. The type of the variable i
6 min read
Spring Boot Interview Questions and Answers Spring Boot is a Java-based framework used to develop stand-alone, production-ready applications with minimal configuration. Introduced by Pivotal in 2014, it simplifies the development of Spring applications by offering embedded servers, auto-configuration, and fast startup. Many top companies, inc
15+ min read