Open In App

Selenium WebDriver - Running test on Safari Browser using Java

Last Updated : 06 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

file
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:

Launch-Safari-Browser-
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

Safari-Navigation-
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

Screenshot-
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

  1. Install the TestNG plugin.
  2. Configure a Jenkins job to run your Maven project.
  3. Add a post-build action to publish TestNG reports.

Azure DevOps

  • Create a pipeline with a Maven task.
images-(4)
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