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
Selenium WebDriver - Running test on Safari Browser using Java
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 ele
5 min read
How to run Selenium Running Test on Chrome using WebDriver
Selenium is a popular open-source tool for automating web browser interactions. It works with different web browsers like Chrome, Firefox, and more, and different programming languages like Python or Java to write tests. What is a Selenium ChromeDriver?ChromeDriver is a separate executable that Sele
3 min read
Selenium WebDriver Handling Radio Buttons Using Java
A platform-independent language that is used to build various applications is known as Java. Java can also be used to automate the web drivers. There are various automation tools available, out of which Selenium is the most common one. We can automate the opening of the website, clicking of push but
4 min read
How to Take a Screenshot in Selenium WebDriver Using Java?
Selenium WebDriver is a collection of open-source APIs used to automate a web application's testing. To capture a screenshot in Selenium, one must utilize the Takes Screenshot method. This notifies WebDriver that it should take a screenshot in Selenium and store it. Selenium WebDriver tool is used t
3 min read
How to Run Safari Driver in Selenium Using Java?
Selenium is a well-known software used for software testing purposes. Selenium consists of three parts: Selenium IDE, Selenium Webdriver, and Selenium Grid. Among these, Selenium Webdriver is the most important one. Using Webdriver, online website testing can be done. There are three main Webdrivers
4 min read
How to Click on a Hyperlink Using Java Selenium WebDriver?
An open-source tool that is used to automate the browser is known as Selenium. Automation reduces human effort and makes the work comparatively easier. There are numerous circumstances in which the user wants to open a new page or perform a certain action with the click of the hyperlink. In this art
4 min read
How to do session handling in Selenium Webdriver using Java?
In Selenium WebDriver, managing browser sessions is crucial for ensuring that each test runs independently and without interference. A browser session in Selenium is identified by a unique session ID, which helps track and manage the session throughout the test. Proper session handling in Selenium W
4 min read
How to refresh a webpage using java Selenium Webdriver?
Refreshing a webpage is often necessary when you want to ensure that your tests or interactions are working with the latest content or to reset the state of a web page during automation. Selenium WebDriver makes this task straightforward with various methods available in Java. This article will demo
3 min read
Selenium Webdriver Handling Checkbox using Java
A set of tools and libraries that allow the user to automate interactions with web browsers is known as Selenium. It is too diverse tool that can handle every operation of a webpage starting from opening the webpage to closing of webpage. In this article, we will see the various steps to handle the
6 min read
Handle Firefox Not Responding While Using Selenium WebDriver using java?
During the usage of Selenium WebDriver with Java and internet applications, the problem of having a âFirefox Not Respondingâ error may be quite frequent when running lengthy or detailed tests. This problem tends to interfere with test flows and thus fails in test cases and returns wrong results. To
3 min read