Java Selenium & Database Testing Lab
โ๏ธ 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.javaMaven 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 correctExecution
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
| Concept | Meaning |
|---|---|
| WebDriver | Browser automation interface |
| ChromeDriver | Chrome-specific WebDriver |
| driver.get() | Navigate to URL |
| driver.getTitle() | Get page title |
| WebElement | Represents HTML element |
| findElement() | Locate element |
| By.name() | Locate by name attribute |
| isDisplayed() | Check visibility |
| isEnabled() | Check enabled |
| getScreenshotAs() | Take screenshot |
| BufferedImage | Image in Java |
| getRGB() | Get pixel value |
| JDBC | Java Database API |
| Connection | DB connection |
| Statement | Execute SQL |
| ResultSet | Query results |
| H2 | Embedded Java DB |
๐ค Viva Questions
โ๏ธ React Concepts โ Inventory Demo
Props ยท State ยท Refs ยท Effects ยท Context ยท Memo โ all in one interactive example.
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]);product
{name}
price:{price}
category: {category}
jsx
count: {count}
Inventory management
setSearch(e.target.value)}/>
total value: {totalValue}
-
{filterProducts.map((p,i)=>(
- {p.name} - {p.price} ))}
๐ 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.