Java Selenium & Database Testing Lab

Complete Practical Experiments โ€” Selenium WebDriver, Visual Testing & JDBC
๐Ÿ“˜ 5 experiments ยท Selenium + JDBC

โš™๏ธ Setup project structure & dependencies

Project structure

selenium-lab/ โ”œโ”€โ”€ pom.xml โ”œโ”€โ”€ Screenshots/ โ””โ”€โ”€ src/ โ””โ”€โ”€ main/ โ””โ”€โ”€ java/ โ””โ”€โ”€ com/ โ””โ”€โ”€ test/ โ””โ”€โ”€ sel/ โ”œโ”€โ”€ Exp2.java โ”œโ”€โ”€ Exp3.java โ”œโ”€โ”€ Exp4.java โ”œโ”€โ”€ Exp4b.java โ””โ”€โ”€ Exp5.java

Maven dependencies

<dependencies> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>4.34.0</version> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <version>2.4.240</version> </dependency> </dependencies>

Selenium Manager (in Selenium 4) automatically downloads the correct ChromeDriver โ€” no manual setup.

Commands

mvn compile mvn exec:java -Dexec.mainClass="com.test.sel.Exp2"

Class name must match package + class: com.test.sel.Exp2

๐Ÿงช Experiment 2 โ€” Page Title Verification

Objective: Verify that Google's title matches "Google".

Concepts

WebDriver ยท ChromeDriver ยท driver.get() ยท driver.getTitle() ยท expected vs actual ยท PASS/FAIL

Complete code

package com.test.sel; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class Exp2 { public static void main(String[] args) throws InterruptedException { WebDriver driver = new ChromeDriver(); driver.get("https://www.google.com"); String expectedTitle = "Google"; String actualTitle = driver.getTitle(); System.out.println("Actual Title : " + actualTitle); System.out.println("Expected Title : " + expectedTitle); if (actualTitle.equals(expectedTitle)) { System.out.println("PASS: Title is correct"); } else { System.out.println("FAIL: Title is incorrect"); } Thread.sleep(2000); driver.quit(); } }

Explanation

WebDriver driver = new ChromeDriver(); โ€” browser-control object.
driver.get("...") โ€” navigates to URL.
driver.getTitle() โ€” returns page title.
actualTitle.equals(expectedTitle) โ€” assertion logic.

Expected output

Actual Title : Google Expected Title : Google PASS: Title is correct

Execution

mvn compile mvn exec:java -Dexec.mainClass="com.test.sel.Exp2"

๐Ÿงช Experiment 3 โ€” Web Element Validation

Objective: Verify Google search box is displayed and enabled.

Concepts

WebElement ยท By ยท findElement() ยท By.name() ยท isDisplayed() ยท isEnabled()

Complete code

package com.test.sel; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class Exp3 { public static void main(String[] args) { WebDriver driver = new ChromeDriver(); driver.get("https://www.google.com"); WebElement searchBox = driver.findElement(By.name("q")); System.out.println("Displayed : " + searchBox.isDisplayed()); System.out.println("Enabled : " + searchBox.isEnabled()); if (searchBox.isDisplayed() && searchBox.isEnabled()) { System.out.println("PASS: Search box is ready"); } else { System.out.println("FAIL: Search box is not ready"); } driver.quit(); } }

Explanation

driver.findElement(By.name("q")) โ€” finds element with name="q".
isDisplayed() โ€” visibility. isEnabled() โ€” interactable.
If locator not found โ†’ NoSuchElementException.

Expected output

Displayed : true Enabled : true PASS: Search box is ready

๐Ÿงช Experiment 4A โ€” Element Screenshot & Bitmap Checkpoint

Objective: Capture search box screenshot and compare pixel-by-pixel with baseline.

Concepts

getScreenshotAs() ยท OutputType.FILE ยท BufferedImage ยท getRGB() ยท visual regression

Complete code (Exp4.java)

package com.test.sel; import java.awt.image.BufferedImage; import java.io.File; import javax.imageio.ImageIO; import org.openqa.selenium.By; import org.openqa.selenium.OutputType; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.io.FileHandler; public class Exp4 { public static void main(String[] args) throws Exception { WebDriver driver = new ChromeDriver(); driver.get("https://www.google.com"); WebElement searchBox = driver.findElement(By.name("q")); File folder = new File("Screenshots"); if (!folder.exists()) folder.mkdir(); File current = new File("Screenshots/current_searchbox.png"); FileHandler.copy(searchBox.getScreenshotAs(OutputType.FILE), current); File baseline = new File("Screenshots/baseline_searchbox.png"); if (!baseline.exists()) { System.out.println("Baseline image not found."); System.out.println("Rename current_searchbox.png to baseline_searchbox.png"); } else { BufferedImage img1 = ImageIO.read(baseline); BufferedImage img2 = ImageIO.read(current); if (img1.getWidth() == img2.getWidth() && img1.getHeight() == img2.getHeight()) { boolean same = true; for (int x = 0; x < img1.getWidth(); x++) { for (int y = 0; y < img1.getHeight(); y++) { if (img1.getRGB(x, y) != img2.getRGB(x, y)) { same = false; break; } } } System.out.println(same ? "BITMAP CHECKPOINT : TEST PASS" : "BITMAP CHECKPOINT : TEST FAIL"); } else { System.out.println("BITMAP CHECKPOINT : TEST FAIL"); } } driver.quit(); } }

Algorithm

Baseline โ†” Current โ†’ check dimensions โ†’ loop every pixel โ†’ compare RGB โ†’ all equal ? PASS : FAIL

getRGB(x,y) returns pixel color. Even tiny difference โ†’ FAIL (exact equality).

๐Ÿงช Experiment 4B โ€” Screenshot Similarity

Objective: Capture browser area, calculate percentage of identical pixels vs baseline.

Concepts

TakesScreenshot ยท getSubimage() ยท similarity = (identical pixels / total) ร— 100

Complete code (Exp4b.java)

package com.test.sel; import java.awt.image.BufferedImage; import java.io.File; import javax.imageio.ImageIO; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class Exp4b { public static void main(String[] args) throws Exception { WebDriver driver = new ChromeDriver(); driver.manage().window().maximize(); driver.get("https://www.google.com"); File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); BufferedImage fullImage = ImageIO.read(screenshot); File folder = new File("Screenshots"); if (!folder.exists()) folder.mkdir(); int width = Math.min(800, fullImage.getWidth()); int height = Math.min(600, fullImage.getHeight()); BufferedImage currentArea = fullImage.getSubimage(0, 0, width, height); File currentFile = new File("Screenshots/current_google_area.png"); ImageIO.write(currentArea, "png", currentFile); System.out.println("Current screenshot saved."); File baselineFile = new File("Screenshots/baseline_google_area.png"); if (!baselineFile.exists()) { System.out.println("Baseline image not found."); System.out.println("Rename current_google_area.png to baseline_google_area.png"); } else { BufferedImage baseline = ImageIO.read(baselineFile); double similarity = compareImages(baseline, currentArea); System.out.println("Similarity : " + similarity + "%"); if (similarity >= 95) { System.out.println("BITMAP CHECKPOINT : TEST PASS"); } else { System.out.println("BITMAP CHECKPOINT : TEST FAIL"); } } driver.quit(); } public static double compareImages(BufferedImage img1, BufferedImage img2) { if (img1.getWidth() != img2.getWidth() || img1.getHeight() != img2.getHeight()) { return 0; } long totalPixels = (long) img1.getWidth() * img1.getHeight(); long samePixels = 0; for (int x = 0; x < img1.getWidth(); x++) { for (int y = 0; y < img1.getHeight(); y++) { if (img1.getRGB(x, y) == img2.getRGB(x, y)) { samePixels++; } } } return (samePixels * 100.0) / totalPixels; } }

Threshold 95% โ€” more tolerant than exact bitmap equality.

๐Ÿงช Experiment 5 โ€” Database Testing (H2)

Objective: Create table, insert student, retrieve and verify.

Concepts

JDBC ยท H2 ยท DriverManager ยท Connection ยท Statement ยท ResultSet

Complete code

package com.test.sel; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class Exp5 { public static void main(String[] args) { try { Connection con = DriverManager.getConnection("jdbc:h2:./StudentDB", "sa", ""); Statement stmt = con.createStatement(); stmt.execute("CREATE TABLE IF NOT EXISTS STUDENT(ID INT PRIMARY KEY, NAME VARCHAR(50), EMAIL VARCHAR(100))"); stmt.execute("DELETE FROM STUDENT"); stmt.executeUpdate("INSERT INTO STUDENT VALUES(1,'Ajay','ajay@gmail.com')"); ResultSet rs = stmt.executeQuery("SELECT * FROM STUDENT WHERE ID = 1"); if (rs.next()) { System.out.println("Record Exists"); System.out.println("ID : " + rs.getInt("ID")); System.out.println("Name : " + rs.getString("NAME")); System.out.println("Email : " + rs.getString("EMAIL")); System.out.println("TEST PASSED"); } else { System.out.println("Record Not Found"); System.out.println("TEST FAILED"); } con.close(); } catch (Exception e) { e.printStackTrace(); } } }

JDBC pipeline

Java โ†’ DriverManager โ†’ Connection โ†’ Statement โ†’ SQL โ†’ H2 โ†’ ResultSet โ†’ verification

execute() (DDL) ยท executeUpdate() (INSERT/UPDATE) ยท executeQuery() (SELECT) ยท rs.next() moves cursor.

๐Ÿ“˜ Quick Revision

ConceptMeaning
WebDriverBrowser automation interface
ChromeDriverChrome-specific WebDriver
driver.get()Navigate to URL
driver.getTitle()Get page title
WebElementRepresents HTML element
findElement()Locate element
By.name()Locate by name attribute
isDisplayed()Check visibility
isEnabled()Check enabled
getScreenshotAs()Take screenshot
BufferedImageImage in Java
getRGB()Get pixel value
JDBCJava Database API
ConnectionDB connection
StatementExecute SQL
ResultSetQuery results
H2Embedded Java DB

๐ŸŽค Viva Questions

What is Selenium?
A framework for automating web browsers.
What is WebDriver?
Core interface for browser automation.
What is ChromeDriver?
WebDriver implementation for Chrome.
What is Selenium Manager?
Auto-manages driver executables.
What does driver.get() do?
Navigates to a URL.
Difference between isDisplayed() and isEnabled()?
isDisplayed() checks visibility; isEnabled() checks interactability.
What happens if findElement() cannot find an element?
Throws NoSuchElementException.
What is bitmap comparison?
Pixel-by-pixel image comparison.
Why use 95% similarity in Exp4b?
Tolerance for minor rendering differences.
What is JDBC?
Java API for database connectivity.
Difference between execute(), executeUpdate(), executeQuery()?
execute() general; executeUpdate() for DML; executeQuery() for SELECT.
What does rs.next() do?
Moves cursor to next row, returns true if exists.

โš›๏ธ React Concepts โ€” Inventory Demo

Props ยท State ยท Refs ยท Effects ยท Context ยท Memo โ€” all in one interactive example.

Total: 0
๐ŸŒž Light ยท 0 products

How this maps to React concepts

  • Props + callbacks: ProductCard component receives name, price, and onBuy.
  • useState: products, search, theme.
  • useRef: nameref, priceref โ€” direct DOM access.
  • useEffect: changes body background/color when theme changes.
  • useContext: ThemeContext provides theme and setTheme to children.
  • useMemo: filterProducts and totalValue are cached.
// Corrected ProductCard with props (no commas) <ProductCard key={product.id} name={product.name} price={product.price} category={product.category} onBuy={() => handleNow(product.name)} /> // useState const [count, setCount] = useState(0); // useRef const nameref = useRef(); <input ref={nameref} /> // useEffect (theme) useEffect(() => { document.body.style.backgroundColor = theme === "light" ? "#fff" : "#333"; }, [theme]); // useContext (ThemeContext) const { theme, setTheme } = useContext(ThemeContext); // useMemo const filterProducts = useMemo(() => { return products.filter(p => p.name.toLowerCase().includes(search.toLowerCase()) ); }, [products, search]);
import React from "react"; import ProductCard from "./ProductCard" const products=[{id:1,name:"sofa",price:8000,category:"furniture"}, {id:2,name:"washing machine",price:15000,category:"electronics"}, {id:3,name:"bedsheet",price:200,category:"clothes"}]; function App() { const handleNow=(productName)=>{ alert(`you clicked buy now for ${productName}`); } return(

product

{products.map((product)=>( handleNow(product.name)} /> ))}
) }; export default App; import React from "react"; function ProductCard({name,price,category,onBuy}) { return(

{name}

price:{price}

category: {category}

) }; export default ProductCard; import React,{useState} from "react"; function App() { const[count,setCount]=useState(0); return(

jsx

count: {count}

) } import React,{useState, useRef, useEffect, useContext, useMemo, createContext} from "react"; const ThemeContext=createContext(); function App(){ const[products,setProducts]=useState([]); const[search,setSearch]=useState(""); const[theme,setTheme]=useState("light"); const nameref=useRef(); const priceref=useRef(); const addProducts= () => { const name=nameref.current.value; const price=parseFloat(priceref.current.value); if(name && price) { setProducts([...products,{name,price}]); nameref.current.value=""; priceref.current.value=""; } }; const filterProducts=useMemo(()=>{ return products.filter((p)=>( p.name.toLowerCase().includes(search.toLowerCase()) )) },[products,search]) const totalValue=useMemo(()=>{ return filterProducts.reduce((sum,p)=>sum+p.price,0) },[filterProducts]) useEffect(()=>{ document.body.style.backgroundColor=theme==="light"?"#fff":"#333"; document.body.style.color=theme==="light"?"#000":"#fff"; },[theme]) return(

Inventory management



setSearch(e.target.value)}/>


total value: {totalValue}

    {filterProducts.map((p,i)=>(
  • {p.name} - {p.price}
  • ))}
) } export default App;

๐Ÿ“Œ How to Study These Experiments

1. Understand the purpose โ†’ 2. Understand each Selenium/JDBC API โ†’ 3. Run the program โ†’ 4. Change one thing โ†’ 5. Break intentionally โ†’ 6. Observe the error โ†’ 7. Rebuild without looking.

Do not memorize line-by-line. Understand flow and API concepts.