How do I connect to a database using Selenium WebDriver for data-driven testing?

Selenium WebDriver is a tool used for automating web application testing, and it is not intended for direct database interactions. However, in data-driven testing, you might want to connect to a database to retrieve test data or verify data after performing some actions through the Selenium WebDriver.

To connect to a database in the context of data-driven testing using Selenium WebDriver, you would use a separate library for database connectivity depending on the programming language you are using. For instance, in Python, you could use sqlite3, PyMySQL, or psycopg2 for SQLite, MySQL, or PostgreSQL databases, respectively. In Java, you would use JDBC (Java Database Connectivity).

Here's how you can connect to a database and use it in conjunction with Selenium WebDriver for data-driven testing:

Python Example

Let's say you're using a SQLite database for simplicity.

import sqlite3
from selenium import webdriver

# Establish a connection to the database
conn = sqlite3.connect('path_to_your_database.db')
cursor = conn.cursor()

# Fetch data from the database
cursor.execute("SELECT * FROM test_data")
rows = cursor.fetchall()

# Set up Selenium WebDriver
driver = webdriver.Chrome(executable_path='path_to_chromedriver')

# Iterate through the rows of data and perform tests
for row in rows:
    test_input = row[0]
    expected_output = row[1]

    # Perform your Selenium actions here, e.g., filling out forms
    driver.get('https://yourwebsite.com/form')
    input_element = driver.find_element_by_id('inputField')
    input_element.send_keys(test_input)

    # Verify the result
    # ... Your verification logic here

# Close the database connection and WebDriver
cursor.close()
conn.close()
driver.quit()

Java Example

For Java, you can use JDBC for connecting to a MySQL database, for example.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class DataDrivenTest {
    public static void main(String[] args) {
        // Set up the database connection
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            conn = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/your_database",
                "username",
                "password"
            );
            stmt = conn.createStatement();
            rs = stmt.executeQuery("SELECT * FROM test_data");

            // Set up Selenium WebDriver
            System.setProperty("webdriver.chrome.driver", "path_to_chromedriver");
            WebDriver driver = new ChromeDriver();

            // Iterate through the database rows and perform tests
            while (rs.next()) {
                String testInput = rs.getString("input_column");
                String expectedOutput = rs.getString("expected_output_column");

                // Perform Selenium actions here
                driver.get("https://yourwebsite.com/form");
                // ... Your Selenium testing logic here

                // Verify the result
                // ... Your verification logic here
            }

            // Close the WebDriver
            driver.quit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try { if (rs != null) rs.close(); } catch (Exception e) {};
            try { if (stmt != null) stmt.close(); } catch (Exception e) {};
            try { if (conn != null) conn.close(); } catch (Exception e) {};
        }
    }
}

Remember to add the JDBC driver to your project's dependencies. You would typically do this by adding a Maven or Gradle dependency if you're using a build tool or by downloading the driver JAR and adding it to your project's classpath.

In both examples, Selenium WebDriver is used to automate the browser actions, while database connectivity is handled through separate libraries that are designed for database interactions. It's important to manage resources properly by closing database connections and WebDriver instances after the tests are completed to avoid resource leaks.

Related Questions

Get Started Now

WebScraping.AI provides rotating proxies, Chromium rendering and built-in HTML parser for web scraping
Icon