Top 100+ Java Selenium Interview Questions for Freshers & Experts

October 20, 2025

I’ve been in that spot where your brain just blanks mid-interview. The interviewer says, “Write a Selenium test that clicks a button,” and suddenly you forget how locators even work. Whether it’s debugging a flaky XPath, explaining implicit waits, or setting up parallel runs, Java Selenium interview questions are the kind that separate people who’ve actually built test frameworks from those who’ve only copied them off GitHub.

When I was grinding through FAANG coding interviews, these questions came up everywhere, in screening calls, take-homes, and on-sites. They’re less about tricking you and more about checking if you can think clearly under pressure. That’s why I put together this guide: clear explanations, runnable snippets, and the kind of real-world answers you can give without sounding rehearsed.

If you want actually to practice this stuff, not just read it, Interview Coder’s AI Interview Assistant lets you run mock interviews, get instant AI feedback, and fix mistakes before the next recruiter call. It’s the tool I wish I had back when I was winging my first Selenium interview at Amazon.

53 Most Asked Java Selenium Interview Questions

Blog image

1. What is Selenium, really?

If I had a dollar for every time someone explained Selenium like it’s some mythical beast, I could probably buy a second monitor for my test suite.

Selenium is a way to make your browser do stuff automatically, like clicking buttons, filling out forms, or testing your site on 17 different versions of Chrome.

It’s free. It works with almost every major browser. It speaks Java, Python, C#, JavaScript, pick your flavor. And because it’s open-source, there’s a vast community that’s already figured out 90% of the problems you’re gonna run into.

If you're trying to land a testing or QA role, Selenium is non-negotiable. If you're an SDET, it’s just another Tuesday.

2. The Four Parts of Selenium (And Why You Shouldn’t Confuse Them)

Selenium isn’t one thing. It’s more like a toolbox. Here’s what’s in it and what actually matters.

Selenium IDE

If you’re new, this is your training wheels. It records your browser actions so you can replay them like a macro. Great for small tests, quick demos, or when your manager asks for a “proof of concept” before lunch.

It was built in 2006 by Shinya Kasatani (legend), and it’s still around, more polished now, but with the same idea.

Selenium RC (RIP)

This one’s basically Selenium’s great-grandparent. It used a server to talk to the browser, which was... slow. Nobody uses this anymore unless they’re maintaining a legacy app from the Jurassic period. Still shows up in interviews, though. Know the name, don’t spend a weekend learning it.

Selenium WebDriver

This is the one you actually use. You write code, and WebDriver makes the browser behave. No extra server. It’s clean, fast, and plays nicely with other testing tools. If Selenium were a band, WebDriver is the frontman.

Selenium Grid

Ever wanted to run your test suite on 15 machines at once while drinking coffee in peace? Grid makes that happen, one hub, many nodes, like distributed browser testing without having to spin up a fleet manually.

3. Why Do People Still Use Selenium?

Honestly? Because it works. And it doesn’t cost anything.

Here’s what I like about it:

  • Works across all major browsers and OSs
  • Supports multiple languages (Java, Python, etc.)
  • Easy to plug into CI/CD
  • Great for reusing tests across projects
  • Parallel execution with Grid = faster feedback

It’s not perfect. But if you're on a budget and need to automate tests across 12 environments by Friday, Selenium’s the friend who shows up with pizza and gets things done.

4. What Is Test Automation?

Test automation writing scripts to do the boring stuff you’d otherwise do manually. Like clicking “Submit” 200 times or checking if that one modal still works on Firefox 78.

In most teams I’ve worked with (especially Agile ones), manual testing is the fallback. Automation is the plan. And if you’re interviewing at big tech companies? Expect them to ask how you’d design the tests and automate them.

Pro Tip

If they say “we use DevOps,” start talking about automation early in the interview. They’ll nod.

5. Real Talk: Is Automation Testing Actually Worth It?

The short answer is yes. Long answer, still yes, but not on day one.

Here’s what you actually get:

More Test Coverage

More bugs caught earlier

Consistency

machines don’t forget edge cases

Speed

tests run while you sleep

Less manual grind

Nobody wants to click the same login button 300 times

Long-term savings

It’s an upfront investment that pays back over time

Just don’t automate everything blindly. Some tests are better left manual (like design feedback or weird user flows). Be smart about it.

6. What’s Selenese? (Yes, it’s a real word)

Selenese is what Selenium IDE uses to talk to your browser. Think of it as Selenium’s command language. It’s not something you’d write in a terminal, but if you use Selenium IDE, you’ll see it constantly.

Three main types:

Actions

things like clicking, typing, selecting

Accessors

grab values (like text or attributes)

Assertions

Check if what you expected actually happened

Don’t memorize the whole list. Just know what each type is used for and be able to give examples.

7. Selenium 2.0 vs 3.0: What Changed?

This comes up more often than you'd think.

Here’s the TL;DR I’d give in an interview:

Selenium 2.0

Merge of Selenium + WebDriver. RC still existed (barely).

Selenium 3.0

RC was finally dropped. WebDriver took the wheel. Fewer bugs, better performance.

So yeah, 3.0 was the update that said, “We’re done supporting old stuff, let’s clean this up.” You’ll still hear 2.0 mentioned because a lot of docs and blog posts were written during that time.

8. What Selenium Actually Tests (Without the Fluff)

Alright, let’s keep this real.

Most people crack open Selenium and immediately get buried in docs and buzzwords. I was one of them. Back when I was grinding for my Amazon SDE internship, I thought “regression testing” was something my therapist should be doing. But no, it’s just code checkups after changes. Not that deep.

Here’s what Selenium actually helps you test:

Regression Testing

You change some code. Now you’re paranoid you broke something. Regression testing is how you sleep at night.

Here’s the cycle:

  • Grab test cases that cover stuff you touched
  • Rank ‘em (critical ones go first)
  • Run them
  • Check what broke
  • Log bugs (or cry, depending on the results)
  • Tweak your suite over time
  • Automate it all so your future self doesn’t hate you
  • Repeat after every update

That’s it. It’s like brushing your teeth, not exciting, but you skip it and things rot.

Functional Testing

This one’s simpler. You’re checking if stuff does what it says on the box.

The process:

  • Figure out what function you’re testing
  • Know what input you’ll feed it and what result you expect
  • Run it
  • See if what happened matches what should’ve happened

It’s like making sure the “Log In” button actually logs you in and doesn’t send your credentials to some void.

9. Selenium Annotations in TestNG (Or: The Part Everyone Skims)

If you’re using TestNG with Selenium, you’ve seen those @Before and @After annotations. If they look like magic spells, here’s the cheat sheet:

  • @BeforeSuite → runs before everything
  • @AfterSuite → runs after everything
  • @BeforeTest / @AfterTest → for the test methods
  • @BeforeClass / @AfterClass → before and after the test class methods
  • @BeforeMethod / @AfterMethod → before and after each test method
  • @BeforeGroups / @AfterGroups → before and after test groups

These are all about setup and cleanup. Don’t overthink it. Just wire up what needs to run before and after your tests, and move on.

10. Web Element Locators: AKA: How to Find Stuff on a Page

Finding stuff on a page is half the battle. Here are the ways Selenium helps you do it:

1. ID

Best-case scenario. Fast and unique.

driver.find_element(By.ID, "loginBtn")

2. Class Name

Works, but classes can be shared across elements.

driver.find_element(By.CLASS_NAME, "button-primary")

3. Name

Often used in forms. Not always unique.

driver.find_element(By.NAME, "email")

4. Tag Name

Useful if you’re selecting by type — like all <input>s.

driver.find_element(By.TAG_NAME, "input")

5. CSS Selector

Flexible, clean. Good if you're familiar with how CSS works.

driver.find_element(By.CSS_SELECTOR, ".form input[type='text']")

6. XPath

The Swiss Army knife. Powerful but ugly.

driver.find_element(By.XPATH, "//input[@type='text']")

7. Link Text / Partial Link Text

Works great for anchor tags.

driver.find_element(By.LINK_TEXT, "Sign up")

XPath is overkill 90% of the time. Use it only when you have no other choice.

11. Waits in Selenium: Because Nothing Loads on Time

Web apps aren’t instant. You click a thing, and it takes a second (or five). Selenium needs to chill and wait sometimes.

Types of Waits

  • Implicit Wait: Sets a global wait time. Selenium keeps checking the DOM until stuff shows up.
  • Explicit Wait: Wait for something specific (like “this button is clickable”). Cleaner and more precise.
  • Fluent Wait: Fancy version of explicit. You get more control over how often to check and how long to wait.

I usually use explicit waits. Implicit waits feel like using a sledgehammer to swat a fly.

12. Browser Navigation Commands: Like the Back Button, But Code

If you’ve ever wanted to automate browser actions like clicking “back” or refreshing, here’s your toolbox:

  • .to("url") → go to a page
  • .back() → go back
  • .forward() → go forward
  • .refresh() → reload the page

That’s it. Just like your browser history, but programmable.

13. driver.close() vs driver.quit(): What’s the Real Difference?

Back when I first started messing around with Selenium, I treated driver.close() and driver.quit() like the same thing. One shut the tab. The other... also shut the tab? Wrong. I learned the hard way after accidentally killing my entire WebDriver session mid-debug. Oops.

Here’s the breakdown, straight up:

Feature

driver.close()

driver.quit()

What it touches

Only the current window or tab

Everything the session owns

WebDriver session

Still running

Totally shut down

Memory cleanup

Minimal

Full cleanup (as it should)

When to use it

You opened a popup and want it gone

You’re done with the whole test

Multi-window behavior

Other windows stay open

Everything goes down with the ship

Moral of the story? Use close() like a sniper. Use quit() like a nuke.

14. Manual vs. Automated Testing: Which One Actually Works?

I’ve done both. One feels like sorting socks by hand. The other feels like building a sock-sorting robot.

Here’s the difference that matters:

Parameter

Manual Testing

Automated Testing

Speed

Slow. You’ll feel it.

Fast. Like, scary fast sometimes.

Effort

Human brain + eyeballs

Tools + scripts + someone who knows what they’re doing

Exploratory Testing

Possible. You can freestyle.

Not really. Scripts follow scripts.

Frameworks Needed

Nah. Just you.

Yep. You’ll need stuff like TestNG, PyTest, etc.

If you’re running one test, go manual. If you’re testing every commit like a real dev team, automate it. There’s no pride in clicking the same button 47 times.

15. Absolute vs. Relative XPath: Which One’s Smarter?

Ever gotten lost because Google Maps gave you step-by-step directions from your house instead of where you’re currently standing? That’s Absolute XPath.

Absolute XPath

Starts from the root of the page and gives you the entire road trip. One tiny change and boom, your whole path breaks.

Relative XPath

Starts from where you are and says, “walk 2 blocks, take a left.” Cleaner, smarter, and way easier to maintain.

Which one do I use 99% of the time?

16. What Selenium Can’t Do (Yes, There’s a List)

I love Selenium. But I won’t lie and pretend it’s perfect. Here’s where it gets annoying:

No Official Support

If it breaks, Stack Overflow is your friend. Or enemy.

Web Only

Want to test a desktop or mobile app? You’ll need something else.

No Image Validation

It can check if an image exists, not if it looks right.

No Built-In Reports

Bring your own TestNG or JUnit setup.

You Need Code

If you’re allergic to code, this isn’t your tool.

17. Same-Origin Policy: AKA “Why Won’t My Script Work?”

Browsers are paranoid for good reason. The Same-Origin Policy blocks your script from poking around pages that didn’t come from the same protocol, same domain, same port, or you’re blocked.

Want to test across domains? Selenium RC had a workaround, a sneaky little proxy trick that made it look like everything was coming from the same place.

Selenium WebDriver is better now, but you still need to know this if you’re writing tests that touch multiple subdomains.

18. Why Selenium Gets So Much Love

Selenium isn’t “popular” because it’s flashy. It’s popular because it just works. Here’s why engineers keep using it:

  • Works with real browsers
  • You can write tests in Java, Python, C#, JS, whatever you want
  • Runs on any OS you can think of
  • Doesn’t hog your RAM
  • Hooks into CI/CD with no drama

It’s not perfect, but it’s reliable. That counts for something.

19. Why I Still Recommend Selenium

People always ask, “Is Selenium still worth learning?” My answer: yeah, if you want to write tests that actually run on real browsers, not just in a lab.

  • It’s free. Like, actually free.
  • It works everywhere.
  • It speaks your programming language.
  • It plays nicely with other tools.
  • It’s even got support for mobile if you hook it up with Appium.

It’s like the Swiss Army knife of web testing. If you're doing web automation and not using it, you’re either overpaying or overengineering.

20. Exception Testing: Breaking Stuff on Purpose

Sometimes your test should crash. Not by accident. On purpose.

If I write code that’s supposed to throw an error (like divide by zero), I don’t want my test suite to panic. I want it to expect that error and chill out.

Here’s what I use:

@Test(expectedExceptions = ArithmeticException.class)

public void testDivideByZero() {

int result = 10 / 0;

}

That test will pass if it blows up the way I told it to. That’s good testing, controlling the chaos, not avoiding it.

21. Waiting for Page Load: No One Likes a Blank Screen

Waiting for a page to load in Selenium? Yeah, you’ve got two choices:

Implicit Wait

Just set it once. Selenium will chill for that long before giving up on elements.

Explicit Wait

You’re waiting for something specific, like that “Login” button to appear.

I’ve been burned hard by elements not showing up on time. Learn from my past life debugging at 2 am.

22. What is Selenium WebDriver: Without the Buzzwords

Selenium WebDriver is how you tell a browser what to do. Open this page, click that button, fill out this form. It’s the go-to tool if you want your browser to behave like a human tester — minus the mood swings.

23. Is WebDriver a Library?

Nope. Not exactly. WebDriver is more of an interface, like a controller for browsers. Libraries sit on top of it (like Selenium bindings for Java, Python, etc.), but WebDriver is the driver’s seat. Literally.

24. Supported Browsers/Drivers: Don’t Limit Yourself

WebDriver plays nice with all the big names:

  • Chrome
  • Firefox
  • Edge
  • Safari
  • Opera

Cross-browser testing? Covered. No excuses.

25. Selenium 4: What Actually Changed

Selenium 4 dropped with upgrades people actually asked for:

  • Better support for modern browsers
  • Cleaner debugging
  • You don’t need to download drivers manually anymore. Small wins.

I’ve moved all my side projects to v4. Worth it just for the new syntax.

26. What does driver.get() Do?

It opens a URL in the browser. That’s it.

You run driver.get("https://example.com") and your test jumps straight into the site.

27. What’s the Deal with navigate().to()?

It’s like driver.get(), but with a different name. Honestly, I’ve used both to the same result. Pick one and don’t overthink it.

28. Can Selenium Test APIs?

Short answer? No.

  • Selenium = browser automation.
  • APIs = backend stuff.

Use Postman or REST Assured for that. Don’t make Selenium do things it wasn’t built for.

29. How Do You Find Elements in Selenium?

Here’s the toolbox:

  • id
  • name
  • className
  • tagName
  • linkText
  • partialLinkText
  • cssSelector
  • xpath

You’ll end up using XPath way more than you want to. That’s just how it goes.

30. XPath nth-child: Targeting the Right Element

Need to grab the nth element? Use this:

(//parent-element/*)[n]

Swap n with a number. Easy.

Related Reading

31. Typing Text and Clicking Links: The Actual Code

Typing? Easy. Clicking links? Also easy.

Full Link Text

driver.findElement(By.linkText("Today’s deals")).click();

Partial Link Text

driver.findElement(By.partialLinkText("marks")).click();

If your link says “Special Marks,” this’ll catch it.

driver.findElement(By.partialLinkText("price")).click();

Yup, that’ll find “Best Price Deals” or “Price Discounts.”

32. Scroll with JavaScript — scrollBy()

Want to scroll? This works:

JavascriptExecutor js = (JavascriptExecutor) driver;

js.executeScript("window.scrollBy(0, 1000)");

That scrolls down 1000 pixels. I use this when sites are lazy-loaded and hide stuff at the bottom.

33. Click a Hyperlink: The Right Way

Exact Match

driver.findElement(By.linkText("Contact Us")).click();

Partial Match

driver.findElement(By.partialLinkText("About")).click();

Good for links like “About Us,” “About This Page,” etc. Click, redirect, done.

34. Check Page Title: Sanity Check

Here’s how you check if the page title is what you expected:

driver.get("https://www.geeksforgeeks.org/");

String actualTitle = driver.getTitle();

String expectedTitle = "GeeksforGeeks - A Computer Science Portal for Geeks";

if(actualTitle.equalsIgnoreCase(expectedTitle)) {

System.out.println("Title Matched");

} else {

System.out.println("Title didn't match");

}

Or just use an Assert:

Assert.assertEquals(actualTitle, expectedTitle);

Yes, this saved me from shipping a broken login test more than once.

35. Hovering Like a Human (Using the Actions Class)

Have you ever tried to hover over a dropdown and your script just... ignores it? Yeah. Been there.

Back when I was prepping for my first big tech internship interview, one of the mock questions had a fancy menu system. I failed the test not because I didn’t know the logic but because I didn’t know how to simulate a simple hover. Brutal.

Anyway, here’s how you actually do it:

Actions action = new Actions(driver);

action.moveToElement(driver.findElement(By.id("id_of_element"))).perform();

That’s it.

  • Create the Actions object
  • Use moveToElement() with your target
  • Call perform() to make it happen

No magic. Just tell the cursor where to go.

36. Want That CSS Value? Ask Nicely.

There was this one time I spent 30 minutes debugging a color change that didn’t happen. Turns out, the element had a sneaky! Important style I didn’t notice. Fun.

Anyway, if you want to peek under the hood and grab the styles the browser sees, here’s what you need:

String backgroundColor = driver.findElement(By.id("header")).getCssValue("background-color");

That line gives you the actual computed CSS value. Works for font-size, color, border, anything you can think of.

37. Page Object Model (POM): Just Use It

Look, you can write spaghetti test code if you want. But if you want to reuse stuff without crying, use Page Object Model. It's just a way to split your locators and actions into separate files, like normal humans who care about clean code. Don’t overthink it.

38. Can You Automate Captcha?

No, that’s the answer.

Selenium can’t read minds, and it can’t solve Captchas. They’re literally built to stop automation. So either skip the test case or solve the Captcha yourself. Don’t waste your time.

39. Dealing with Windows Popups

Selenium doesn’t talk to your OS. If a Windows file picker or alert pops up, Selenium’s like, “Not my problem.”

If you really need to test it, use AutoIT or the Robot class. They're outside Selenium’s world, but they can hit native popups just fine.

40. Screenshot or It Didn’t Happen

You fixed the bug. Cool. But unless you grab a screenshot, nobody’s gonna believe you.

Here’s how I grab a screenshot and mark the element:

FileUtils.copyFile(File, new File("path/to/save.jpeg"));

JavascriptExecutor js = (JavascriptExecutor) driver;

js.executeScript("arguments[0].style.border='3px solid red'", element);

Saves the pic. Adds a red border. Send it to your manager and sleep well.

41. Selenium vs QTP: Why Bother with QTP?

Selenium is free. QTP is not. Selenium works with every language you already use. QTP… doesn't.

Unless you’re working at a company stuck in 2008, nobody’s picking QTP anymore. That’s the tweet.

42. Data-Driven vs Keyword-Driven Frameworks

Quick difference:

Data-Driven

You change the input data, not the code

Keyword-Driven

You use readable actions like “ClickButton” or “EnterText” in spreadsheets

Both help non-coders run tests, but if you’re an engineer? Pick what’s faster to maintain. That’s it.

43. getWindowHandle vs getWindowHandles

getWindowHandle() gives you the current window ID.getWindowHandles() gives you all of them.

You’ll need both if you want to switch between tabs or pop-ups. Just make sure you’re switching back to the right one. Otherwise, you’ll be clicking buttons on an invisible window.

44. What Even Is a Selenium Maven Project?

You don’t need Maven, but if you want to keep your dependencies clean and avoid a folder full of random JARs, Maven’s your friend.

It helps you:

  • Auto-download WebDriver jars
  • Handle project builds
  • Stop copy-pasting libraries like a caveman

45. Object Repository: AKA "Where Are My Locators?"

Have you ever changed one button ID and broken 20 tests? That’s why we use an Object Repository.

It’s just a separate file where you store all your locators. Update them once. Everything else stays intact. Saves your sanity.

46. XPath: Use Relative, Ditch Absolute

Absolute XPath is a trap.

//input[@id='fakebox-input']

/html[1]/body[1]/div[6]/div[...]

Use Relative XPath. It survives layout changes. Absolute is for people who hate the future.

47. Switching Windows in Selenium

You click something. A new tab opens. Selenium's still staring at the old one like a confused intern.

You need to switch.

Here’s the approach I use during testing:

String parentId = driver.getWindowHandle();

Set<String> allIds = driver.getWindowHandles();

for (String id: allIds) {

if (!id.equals(parentId)) {

driver.switchTo().window(id);

break;

}

}

Switch. Do your thing. Close. Then go back to the parentId classic tab-hopping strategy.

48. Implicit vs. Explicit Waits: Which One Actually Gives You Control?

Look, I used to just throw in Thread.sleep() and pray, rookie mistake. The truth is, when you're starting with Selenium, it's not apparent why your tests keep breaking even though the app seems fine. That was me running tests at midnight, wondering why it failed this time. Here's where understanding Implicit vs Explicit waits saves your sanity.

Let me break it down like I wish someone had for me:

If you're just prototyping, Implicit might cut it. But when things get real, when you're juggling popups, async data, or weird loading times, Explicit waits are your safety net.

49. driver.close() vs. driver.quit(): Don't Mix These Up

I’ll keep this one sim

Implicit Wait

  • Kicks in globally, applies to all element searches.
  • Waits a bit before throwing a “NoSuchElement” error.
  • Less control — it’s “set it and hope.”
  • Can’t target specific elements or conditions.
  • Easier to start with, quick to set up.
  • Can still be flaky if the UI is slow or inconsistent.

Explicit Wait

  • You tell it exactly what to wait for (element, condition, etc.).
  • Gives complete control — wait until this thing appears or is clickable, visible, etc.
  • Built for targeting specific scenarios.
  • More reliable long-term for dynamic UIs.
  • Handles UI hiccups and slow loads like a champ.ple: If you've ever written a test that closes your entire session when you only meant to shut a tab, yeah, been there.

Here’s the difference:

Command: driver.close()

What it Does: Closes the current tab or window. Your WebDriver session stays alive.

Command: driver.quit()

What it Does: Nukes everything. Shuts down the session and all windows. Done.

Rule Of Thumb

close() is surgical. quit() is a clean kill. Use accordingly.

50. Submitting a Form: Actual Code That Works

People love to over-complicate this. But if you're just trying to test a form submission with Selenium, here's a straight-up working example.

Step 1: Set Up a Simple Form

Let’s say you’ve got a form with FirstName, DOB, Email, inputNumber, and a gender radio button.

Step 2: Here’s the Code That Fills and Submits It

// Setup

WebDriver driver = new ChromeDriver();

driver.get("your-webpage-url");

// Fill the form

driver.findElement(By.id("FirstName")).sendKeys("Ram");

driver.findElement(By.id("DOB")).sendKeys("19-01-2001");

driver.findElement(By.id("Email")).sendKeys("[email protected]");

driver.findElement(By.id("inputNumber")).sendKeys("1234567890");

driver.findElement(By.id("Male")).click();

// Submit

driver.findElement(By.cssSelector("button[type='submit']")).click();

// Read the alert

Alert alert = driver.switchTo().alert();

System.out.println("Alert says: " + alert.getText());

// Clean up

driver.quit();

Output

Your browser launches, the form fills itself out, and boom, you get an alert with the data. Done.

51. Deleting Cookies: 2 Ways That Actually Work

You can manually click around in browser settings, or you can write one line and be done.

Option 1: Programmatically (Because You're Smart)

driver.delete_all_cookies()

Works in Python, Java, and JavaScript.

Option 2: The Manual "Burn It All Down" Way

Not recommended, but here’s how you'd do it:

  • Navigate to: driver.get("chrome://settings/clearBrowserData")
  • Find the “Clear Data” button.
  • Click it using Selenium if you’re feeling fancy

But seriously, just use the method in Option 1.

52. Frames: How to Not Get Trapped Inside One

Frames are like annoying little iframes hiding real content. You think you're clicking a button, but nothing happens because you're not inside the frame.

Here’s how I handle it:

Step 1: Spot the Frame

  • Right-click → "This Frame" shows up = yep, it’s a frame
  • Or inspect the page for <iframe> tags.

Step 2: Get in

driver.switchTo().frame("frameName") // or by index or element

Step 3: Do Stuff Inside the Frame

Same as any standard page. Click, type, whatever.

Step 4: Get Out

driver.switchTo().defaultContent()

53. Cross-Browser Testing: Not Optional

Let’s be honest. If your app only works on Chrome, you’re gonna have a bad time when your PM pulls it up in Firefox and it looks like Craigslist in 2002.

Here’s what cross-browser testing actually gives you:

Real-World Stability

Browsers are weird. They render HTML differently. Selenium helps catch these before your users do.

Broader Reach

Not everyone uses Chrome Shocker, I know. Testing across browsers results in a more usable product.

Fewer Late-Night Slack Emergencies

Bugs caught early = no emergency Zooms at 11 PM.

Why I Use Selenium for This

  • It automates all of it. I don’t care if it’s Edge, Safari, or Chrome; I can run them all.
  • No need to rewrite tests in different languages. Selenium’s cool with Java, Python, JS.
  • Open-source. No license. No nonsense.

Related Reading

30 Intermediate Level Selenium Interview Questions

Blog image

1. Typing into an input box

How Do You Type Text Into An Input Field Using Selenium?

This is interview warm-up territory. If you miss this, the rest of the loop is toast.

WebElement email = driver.findElement(By.id("email"));

email.sendKeys("[email protected]");

WebElement password = driver.findElement(By.id("password"));

password.sendKeys("abcdefgh123");

Pro Tips (The Stuff They Don’t Tell You)

  • Call .clear() first if the field might have leftover junk.
  • Don’t trust slow-loading elements; use explicit waits with elementToBeVisible.
  • Your locator game matters. id > name > css > xpath in that order, stability-wise.

2. Clicking a hyperlink

How Do You Click On A Link With Selenium

You’re not just “clicking a thing,” you’re proving you understand locators and timing.

driver.findElement(By.linkText("Today’s deals")).click();

driver.findElement(By.partialLinkText("Service")).click();

Real talk

  • linkText and partialLinkText only work for visible anchor text.
  • If the link text is dynamic (looking at you, JS SPAs), switch to CSS or XPath.
  • Always pair clicks with waits. No one wants a flaky StaleElementReferenceException surprise.

3. Scrolling the page

How Do You Scroll Down Using Selenium?

You cheat. You use JavaScript.

JavascriptExecutor js = (JavascriptExecutor) driver;

js.executeScript("window.scrollBy(0,1000)");

What I Actually Use In Real Tests

js.executeScript("arguments[0].scrollIntoView(true)", element);

This forces lazy-loaded junk into view, like those job apps with infinite scroll. Pro move? Combine it with WebDriver waits and call it a day.

4. Verifying The Page Title

How Do You Check If The Page Title Is What You Expect?

You’re either writing a pass/fail check or defending yourself when CI/CD starts yelling.

String actualTitle = driver.getTitle();

String expectedTitle = "abcdefgh";

if(actualTitle.equalsIgnoreCase(expectedTitle)) {

System.out.println("Title matched");

} else {

System.out.println("Title didn't match");

}

Cleaner way (and what most of us use):

Assert.assertEquals(actualTitle, expectedTitle);

Test Stability Tip

If titles change dynamically after load, add an explicit wait for the title or use retry logic. Nothing’s worse than a test failing because the app took an extra 200ms.

5. Hovering with your mouse

How Do You Simulate A Hover Over A Web Element?

You bring in the Actions class. Think of it like Selenium’s muscle memory for doing human-ish things.

Actions action = new Actions(driver);

action.moveToElement(driver.findElement(By.id("searchbox"))).perform();

Use this when

  • You want tooltips to show up.
  • Menus drop down on hover.
  • You need to fake mouse movement because JavaScript devs got creative.

Just don’t forget to combine with wait timing, it's everything.

6. Get CSS Properties Like a Human (Not a Bot)

Have you ever spent 30 minutes wondering why your button looks like it's been hit with Comic Sans energy, only to find out the CSS got overridden? Yeah, same. Here's how I pull CSS values mid-test:

driver.findElement(By.id("email")).getCssValue("font-size");

That’s it. .getCssValue() gives you what the browser actually applied, which is good for catching weird font issues or margin creep in UI tests. Comes back as a string, so pair it with assertions if you're into clean test reports.

7. Page Object Model (POM): The Reason I Didn’t Quit UI Testing

Back when I was brute-forcing my way through test scripts, I was one flaky test away from rage-quitting. Then I met Page Object Model.

Think of it like this: every page = its own class. You stash all the locators and actions there, like a drawer full of Lego pieces. Now tests just say, “click login button,” not “find XPath and pray.”

If you’re not using POM, your codebase will age like milk.

Pro Move

Use PageFactory or roll your own wrapper. Makes maintenance way less painful, especially if you’re on a Maven + TestNG stack.

8. Can Selenium Automate Captcha?

Short answer? No.

Long answer? Still no.

Captcha exists to keep bots out. Selenium is a bot. So don’t try to outsmart the system, you won’t. For test environments, stub it. For prod? Don’t touch it unless you like compliance headaches.

9. Dealing with Windows Pop-ups Without Losing Your Mind

Selenium is for browsers. If a Windows pop-up shows up? It’s like asking a fish to ride a bike.

But if you have to deal with them:

AutoIT

Suitable for scripting Windows UI clicks.

Robot

Think of it like Selenium’s keyboard sidekick.

Sikuli

Image-based, use it when locators fail you.

For browser alerts, just use WebDriver’s Alert API. Way easier.

10. Taking Screenshots (Because Things Break)

Tests fail. Clients ask why. Show, don’t tell.

File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

Dump it into your failure logs. Timestamp it. Done. If you're using TestNG or JUnit, wire it into your listeners/rules and let it run automatically when stuff explodes.

11. Why People Use Selenium Instead of QTP

Let’s keep it real: Selenium is free. QTP makes your wallet cry.

Also:

  • Selenium works with Java, Python, and JS. QTP doesn’t.
  • Selenium runs on Windows, Mac, Linux. QTP doesn’t.
  • Selenium is script-friendly QTP, not so much.

And yeah, it plugs into Jenkins, cloud grids, and all the good stuff.

12. Data-Driven vs. Keyword-Driven Testing

Data-Driven

You keep test data (like inputs) separate from scripts. Think: test logic in one file, values in Excel/JSON/etc.

Keyword-Driven

You make a list of “actions” like Click, EnterText, and map those to actual commands. Feels like training your intern.

You can combine both. Most folks do. Especially with TestNG’s @DataProvider if you're on Java.

13. getWindowHandle vs getWindowHandles

Quick one:

  • getWindowHandle() → gives you the current tab's ID.
  • getWindowHandles() → gives you all open tabs/windows.

When switching tabs, save the original handle:

String parent = driver.getWindowHandle();

Then later, boomerang back to it with:

driver.switchTo().window(parent);

Use it when your test flow opens popups, downloads, or any multi-tab thing.

14. What’s a Selenium Maven Project?

Think of Maven as a personal assistant that handles all your imports, builds, and dependencies.

With a pom.xml, you can:

  • Pull in Selenium, TestNG, WebDriverManager, etc.
  • Run your suite from the CLI.
  • Set it up in Jenkins for CI without tears.

Maven + Selenium = fewer headaches when scaling your test setup.

15. Wait, Where’s Number 15?

It’s not missing. It’s just a good reminder that interviews and blog lists don’t always go 100% as planned.

So if you blank on a method or forget a syntax detail, chill, nail the basics: locators, waits, and clean test structure. That’s what interviewers care about anyway.

16. Object Repository definition

What’s an Object Repository?

Suppose you’re hardcoding locators all over the place. Welcome to chaos. An Object Repository is just a cleaner way to keep your stuff organized. Think of it like a label maker for all your buttons, fields, and links instead of having 50 scattered Post-Its.

I used to jam XPath strings directly into my test cases, a big mistake. When the UI changed, everything broke, and I had no clue what to fix. Storing locators in page classes or separate files (like .properties or .xml) saved me hours of “why isn’t this clickable?” debugging.

17. What a WebElement is and how to use it

What’s a WebElement actually doing?

You can’t interact with something in Selenium without grabbing hold of it first. That’s where WebElement comes in; it’s your handle to anything HTML on the page.

You find it, then you do stuff with it:

  • click()
  • sendKeys()
  • getText()
  • getAttribute()
  • isDisplayed()

Most beginners spam these methods everywhere. What did I learned? Wrap these inside your own helper methods, cleaner code, fewer mistakes, and way easier to maintain when you're refactoring.

18. Type Without sendKeys Using JavaScript

What if SendKeys stops working?

Happens more than you'd think, especially on fancy UIs with weird JavaScript behavior or content-editable fields. When sendKeys() gives up, go full hacker-mode and use JS directly:

JavascriptExecutor jse = (JavascriptExecutor) driver;

jse.executeScript("document.getElementById('email').value='[email protected]'");

It’s fast, and it works, but always double-check with getAttribute("value") to make sure the field actually got updated.

19. Select Dropdown Values With The Select Class

Dropdowns Aren't All The Same

If you're lucky, the dropdown is a proper <select> tag. That’s when you can use the built-in Select class.

WebElement menu = driver.findElement(By.id("dropdown"));

Select dropdown = new Select(menu);

dropdown.selectByIndex(2);

dropdown.selectByValue("books");

dropdown.selectByVisibleText("The Alchemist");

Clean and simple. If it’s a custom dropdown built with divs and spans (because someone got too creative), you're gonna need XPath or Actions to simulate clicks manually.

20. switchTo usage for windows and frames

How Do You Deal With Popups, Tabs, or iframes?

Selenium’s switchTo() is what lets you move focus around. Each browser window gets a unique ID, called a window handle. You can switch to one like this:

String handle = driver.getWindowHandle();

driver.switchTo().window(handle);

Or loop through all of them:

for (String handle: driver.getWindowHandles()) {

driver.switchTo().window(handle);

}

Also works with:

  • driver.switchTo().frame(...) for iframes
  • driver.switchTo().alert() for JS alerts

Don’t forget to call driver.switchTo().defaultContent() when you’re done with a frame, or you’ll be clicking on stuff that doesn’t exist.

21. Upload files via sendKeys or Robot

How Do You Upload A File?

No upload button? No problem. If the input tag is like <input type="file" />, just send the file path directly:

WebElement upload = driver.findElement(By.id("uploadfile"));

upload.sendKeys("D:\\SeleniumInterview\\UploadFile.txt");

If that doesn’t work (hello, native OS dialogs), use the Robot class or AutoIt to simulate keypresses. I usually default to sendKeys() and only break out Robot if the basic way fails.

Also, use relative paths if you're pushing tests to CI. Hardcoded file paths will break faster than you can say “build failed.”

22. Set Browser Window Size Or Maximize

Can You Control The Browser Window Size?

Yep. Whether you want to go full-screen or mimic a mobile viewport, you’ve got options.

To maximize:

driver.manage().window().maximize();

To set a specific size:

Dimension d = new Dimension(400, 600);

driver.manage().window().setSize(d);

Want to get fancy with JavaScript?

((JavascriptExecutor)driver).executeScript("window.resizeTo(1024, 768)");

Suitable for responsive testing. Combine with screenshots if you want to make sure your layout doesn’t break at different sizes.

23. When to Use findElement() vs findElements()

This one tripped me up early on.

I remember debugging for 45 minutes, wondering why only one checkbox was getting selected out of the five on the page. Spoiler: I was using findElement() when I needed findElements().

findElement() gives you the first match. Just one. That’s it. WebElement element = driver.findElement(By.id("example"));

findElements() returns all the matches — packed into a list. List<WebElement> elementList = driver.findElements(By.id("example"));

A couple of heads-ups

  • findElement() throws NoSuchElementException if nothing's found.
  • findElements() just returns an empty list, which is a lot nicer during test runs.

I use lists for stuff like pagination checks or making sure all price tags render on a product page.

24. Pause on Exception in Selenium IDE

Clicking through the IDE, setting up a quick test, then boom, an exception.

Selenium IDE gives you a "pause on exception" button in the top right. Hit it, and the script stops right at the line that broke. From there, you can debug it in real-time without having to re-run the whole test case.

It’s not magic, but it’s convenient when you’re prototyping or recording flows.

For heavier lifting (like WebDriver suites), you’re better off with logs, breakpoints, or straight-up printing everything like it’s 2010.

25. Handling Those Annoying Login Pop-Ups

Basic auth pop-ups are the worst. They don’t show up in the DOM, so your regular locators won’t catch them.

Here’s how I deal with them:

WebDriverWait wait = new WebDriverWait(driver, 10);

Alert alert = wait.until(ExpectedConditions.alertIsPresent());

alert.authenticateUsing(new UserAndPassword("user", "password"));

If the browser lets you, you might be able to sneak the creds into the URL like:

https://user:[email protected]

But don’t count on Chrome and Firefox keeping patching that out. Use the Alert API if you're serious.

26. Single vs Double Slash in XPath

Quick refresher:

/ = absolute path (starts at the root) /html/body/div[2]/div[1]/div[1]/a

// = relative path (starts anywhere) //div[@class="qa-logo"]/a

I always go with the double slash because absolute paths break the moment someone adds a banner or new div. You want your selectors to survive homepage redesigns.

Also worth learning tricks like contains() or targeting with multiple attributes. XPath is like regex for the browser, ugly, but powerful.

27. How to Spot Broken Links with Selenium

If you’re QA-ing a site with a ton of outbound links, broken ones make you look bad.

Here’s My Basic Flow

Grab all the <a> tags: List<WebElement> links = driver.findElements(By.tagName("a"));

Loop Through Them for (WebElement element: links) {

String url = element.getAttribute("href");

verifyLink(url);

}

Check HTTP Status URL link = new URL(url);

HttpURLConnection httpConn = (HttpURLConnection) link.openConnection();

int code = httpConn.getResponseCode();

if (code != 200) {

System.out.println("Broken link: " + url);

}

Skip links that start with mailto: or javascript:, those aren’t absolute URLs.

Want to speed it up? Link checks async. Otherwise, your test will crawl like it’s on dial-up.

28. Non-Functional Test Tools (aka Stress Test Buddies)

Performance testing is a whole different beast from UI clicks.

Here are some of the tools folks use when Selenium can’t do the job:

  • JMeter
  • LoadRunner
  • WebLoad
  • Gatling
  • Neoload
  • Apache Bench
  • Silk Performer

If you’re just dipping your toes, start with JMeter. It plays nicely with CI, and you can ramp up virtual users without much config pain.

29. CI Tools That Work with Selenium

If you're running tests, manually stop. Just stop.

Selenium works with every CI/CD tool. These are the ones I’ve used:

  • Jenkins
  • GitHub Actions
  • Travis CI
  • CircleCI
  • Bitbucket Pipelines
  • AWS CodePipeline
  • Azure DevOps

Wire them up with Maven or TestNG, and you're good to go. For scaling, toss in Selenium Grid or use a service like BrowserStack.

Pro tip: parallelize tests. Don’t waste time running them one after the other like it’s 2009.

30. Launching Firefox with WebDriver (Old-School but Reliable)

Here’s the simplest way to launch Firefox:

WebDriver driver = new FirefoxDriver();

driver.get("https://google.com");

Make sure geckodriver is in your PATH, or use WebDriverManager to skip the manual setup.

Running In CI? Go Headless

FirefoxOptions options = new FirefoxOptions();

options.setHeadless(true);

WebDriver driver = new FirefoxDriver(options);

That’s it. Firefox might be slower than Chrome, but it’s still solid for debugging layout issues or running cross-browser suites.

Related Reading

  • Jira Interview Questions
  • Python Basic Interview
  • Angular 6 Interview Questions
  • Java Selenium Interview Questions
  • Questions To Ask Interviewer Software Engineer
  • Software Engineer Interview Prep
  • Best Job Boards For Software Engineers
  • Coding Interview Platforms
  • Technical Interview Cheat Sheet
  • Common C# Interview Questions
  • Leetcode Cheat Sheet
  • Coding Interview Tools
  • RPA Interview Questions

18 Advanced-Level Selenium Interview Questions

Blog image

1. Cross-Browser Confidence: Why Your Selenium Suite Shouldn’t Be a Chrome-Only Club

Look, I’ve been burned here. Everything worked great in Chrome, I was feeling good, shipped the build and boom: layout was broken on Safari, buttons didn’t respond in Firefox, and QA was blowing up my Slack at 9 PM.

If your Selenium tests only run on one browser, you’re not testing reality you’re testing a fantasy. Users aren’t all Chrome power-users. They’re your aunt on Edge, your coworker’s Android stock browser, or that one person still using Opera for some reason.

Why This Matters

  • Browsers don’t agree on much, from rendering quirks to JS engine differences; things can and will break.
  • Cross-browser testing lets you catch dumb bugs before your users do.
  • It’s not optional if you want to look like you know what you’re doing.

Why I Use Selenium For This:

  • It’s open-source, no license nonsense.
  • You can automate across Chrome, Firefox, Safari, Edge, and even the weird ones.
  • It plays nicely with most languages and test frameworks.

Testing everywhere used to be a pain. With Selenium, it’s just a config file and some patience.

2. Speed vs. Stability: The Tradeoff You’ll Feel With Parallel Execution

Early on, I thought parallel test runs were going to be my cheat code. Double the tests, half the time. Until my CI started throwing weird errors, random fails, and the kind of bugs that only show up when you’re not looking.

Parallel execution sounds excellent, and it is, but it’s a stress test for your suite. You’ll find out real quick how “independent” your tests really are.

Here’s What Can Go Wrong

  • Shared test data turns into a minefield. One test writes something, another reads it, and suddenly they’re both failing.
  • Some tests expect a specific order. You run them out of order, and things break silently.
  • Your laptop fans become jet engines, especially if you’re spinning up five Chrome instances at once.

Real Talk

  • EdgeDriver doesn’t like running in parallel unless you treat it gently.
  • Race conditions sneak in when your setup/teardown logic isn't airtight.
  • Debugging parallel test flakiness will make you question your life choices.

My Advice

  • Keep your tests dumb and isolated.
  • Use cloud-based Selenium grids if your machine can’t handle the heat.
  • Invest in good logs; you’ll need them.

Parallel is worth it, but only if you treat it like a real engineering problem, not a checkbox.

3. CI Pipeline Stuff That Actually Works: Wiring Selenium Into Jenkins

Back when I was grinding LeetCode and building side projects, I thought CI was just for big companies. Now I won’t push a PR without it. Hooking Selenium into Jenkins is the difference between “I think this works” and “This breaks before it hits staging.”

What I Do

  • Set up your Jenkins job to trigger on PRs or pushes to main.
  • Add your test suite as a build step.
  • Archive test reports and screenshots for failed cases (trust me, you'll want these).

No more “works on my machine” excuses. No more late-night bug reports from PMs. Just clean, repeatable builds that give you confidence.

1. Jenkins Setup That Doesn't Suck

Install What You Actually Need

Skip the plugin rabbit hole. Just grab:

  • Pipeline (for scripted jobs)
  • Git (unless you’re coding in Notepad and uploading zips)
  • Anything browser-specific if you’re testing across platforms (e.g., BrowserStack Plugin)

Set up your JDK. Jenkins needs Java to do anything. Make sure it points to your installed JDK, not the fake one Jenkins sometimes pretends to install.

2. Get Your Selenium Tests Ready

  • Keep Your Tests Organized: Split your test code into modules or classes. You’ll thank yourself when things break (they will).
  • Don’t Mess Up Dependencies: Whatever build tool you use (Maven/Gradle), make sure it actually pulls everything Jenkins needs. Local ≠ Jenkins.
  • Use a Real Framework: I started with raw scripts, which was a bad idea. Use TestNG or JUnit; they make test execution and reporting less painful, especially when things get messy.

3. Build a Jenkins Job (The Way That Works)

Job Type

  • Use Pipeline if you know what YAML is
  • Freestyle Project, if you want checkboxes and dropdowns

Triggers

  • Manual if you’re testing
  • Git webhook if you want it to run when code changes
  • Scheduled if you like 2 am surprises

Steps That Actually Matter

  • Pull code Use Git plugin
  • Install dependencies like the Maven install step
  • Run the tests, Shell commands, or batch scripts, your call
  • Pass environment variables for browsers/devices
  • Capture logs and reports. Jenkins needs proof that your tests didn’t just fail silently.
  • Use JUnit/XUnit to make it all look pretty in the Jenkins dashboard.

4. Page Factory: You Either Get It or You Don’t

At first, I thought Page Factory was just another Selenium buzzword. Turns out, it’s a lifesaver when your tests go beyond two buttons and a login form.

Here’s the deal:

  • @FindBy annotations remove the need to call driver.findElement everywhere
  • It auto-initializes stuff the moment the object is called, less junk code, more clarity.
  • Your tests read like they were written by someone who gives a damn

Bonus

When your UI changes (and it will), you update locators in one file, not 50. You’re welcome.

5. Why I Stick With TestNG (And You Probably Should Too)

You’ll hear folks argue about frameworks like it's a sport. I don’t care. TestNG just works.

Readable and Organized

  • Use @Test, @BeforeTest, @AfterTest like bookmarks for your sanity
  • Group tests however you want (feature, user flows, etc.)

Serious Testing Power

  • DataProvider lets you stop copy-pasting the same test with new values
  • Parallel tests = faster feedback = less time watching Jenkins spin
  • Dependencies help you run things in order, like logging in before checking out.

Reporting That Makes Sense

  • It gives you clean HTML reports of failures, errors, and what broke
  • Add Log4j, and you can even track what went wrong before the crash

Also: It’s free. That matters more than people admit.

6. Waiting in Selenium: Don’t Just Guess

If you’ve ever used Thread.sleep(5000) because something didn’t load, you’re not alone. But please stop.

Implicit Wait

Sets a global timeout. Works, but it’s dumb to wait even if stuff’s already there.

Explicit Wait

Smarter. Waits only when needed. Use it for buttons that take a second to show up.

Fluent Wait

This one’s for the control freaks. You decide how long to wait, how often to check, and what to do if stuff doesn’t show. Great when dealing with flaky elements.

Thread.sleep()

Look… if you're using this, you're just asking for problems. Use it once while debugging and never again.

7. Use Selenium Grid: Or Prepare to Suffer

Testing on one machine is cute until your app breaks on Safari or Firefox.

Here’s what Grid gives you:

Speed

Run tests in parallel. Saves hours.

Coverage

Test across real browsers and devices. Not just Chrome on your machine.

Scalability

Add more machines when your suite grows. Works like adding team members without needing coffee for them.

Money-saving

Use cloud infra like Sauce Labs or BrowserStack. You get device coverage without buying actual devices.

8. Assert Like a Boss: Why Assertions Actually Matter

Let’s be real, writing tests without assertions is like sending a robot to clean your house and never checking if it actually cleaned anything.

When I first started using Selenium, I used to run my scripts, sit back, and assume everything worked because “no errors popped up.” Big mistake. Assertions are what tell you if your test actually passed, not just that it didn’t crash.

Here’s how it works, in plain English:

Step 1

Selenium does something, clicks a button, fills a form, whatever.

Step 2

You tell it what should happen next. A message appears or a new page opens.

Step 3

The assert statement checks if what really happened matches what should have happened.

Step 4

If it doesn’t match, Selenium throws a fit (and that’s a good thing). It’s your cue that something broke before your users find out.

Think of assertions as your personal truth detector for automation. Without them, you’re just hoping your test worked. With them, you know it did.

9. Know the Limits: When Selenium Works, and When It’s Just Annoying

Selenium’s great, but it’s not magic. Some people treat it like it can test anything that has pixels. It can’t.

Here’s what I’ve learned after breaking way too many tests:

Cross-Browser Madness

Different browsers handle code differently. A test that passes on Chrome might fail on Safari for no good reason.

Speed

Big websites + too many elements = slow tests. Selenium waits for the browser to respond, and sometimes the browser’s just lazy.

Dynamic Elements

You know those IDs that change every time you reload a page? Yeah, Selenium hates those.

Mobile Apps

Nope. Selenium’s a web-only tool. If you want mobile, use Appium or something similar.

Desktop Apps

Same deal, you’ll need other tools. Selenium’s not made for that life.

The trick is knowing what Selenium’s good at browser testing and not forcing it to be something it’s not.

10. Driver vs. Element: Stop Mixing Them Up

If you’ve ever confused WebDriver and WebElement, welcome to the club. I did too when I started.

Here’s the simplest way I explain it to new engineers I mentor:

  • WebDriver is like your car’s steering wheel it controls the whole browser.
  • WebElement is like one specific button inside the vehicle maybe the radio or the AC knob.

Feature

WebDriver

WebElement

Purpose

Controls the entire browser

Targets one specific item on the page

Scope

The full browser window or tab

A single button, form field, or image

Interactions

Opens pages, navigates, quits, refreshes

Clicks, types, reads text, submits forms

Example

driver.get("https://example.com")

element = driver.find_element_by_id("login")

Analogy

Remote control for the TV

The specific channel button you press

Common Methods

get(), quit(), switch_to()

click(), send_keys(), get_attribute()

Once you get this difference, Selenium suddenly stops feeling confusing and your scripts stop acting weird for no reason.

11. Database Checks with UI Steps: How I Validate Stuff Without Clicking Into a DB Console

Let’s get something straight that selenium doesn’t touch your database. It’s a front-end spy—a UI button smasher. But sometimes you need to know if that click actually did something real behind the curtain.

So what do I do? I cheat a little. Here's how:

  • Trigger stuff on the UI like adding an item to the cart or submitting a form.
  • Then I check the DB separately using scripts or tools. It's like placing an order and sneaking into the kitchen to see if anyone's cooking.
  • If I’m working in a team, we sometimes mock the database with something like Mockito. It acts like a fake backend that responds the way we hope the genuine one will.
  • If I want to get more hands-on, I use something like JDBCTest to query the database directly. Fair warning though: feels like writing raw Structured query language (SQL) in the dark without auto-complete.
  • Some folks I work with love using tools like Robot Framework or Cypress with Selenium, because they’re pre-wired to do this better than Selenium solo.

Selenium by itself won’t tell you what’s happening in the DB. But there’s always a workaround if you’re scrappy enough.

12. Cucumber Isn’t Just for Salads: It’s How I Got My PM to Read Test Cases

I once had to explain a Selenium test to a product manager using… Google Slides. Never again.

That’s when I started using Cucumber.

Here’s the deal:

Selenium does all the browser stuff clicks, typing, etc. But the code? Not exactly bedtime reading.

Cucumber acts like the translator. It speaks in Gherkin, which looks like a script straight out of a high school play. Example:

  • Given I add three items to the cart
  • When I click “Checkout”
  • Then I should see a confirmation page

Why it’s legit:

  • Non-coders (your boss, your PM, even your QA intern) can actually read what the test does.
  • You stop obsessing over code structure and just focus on what matters: “what should the user see?”
  • Those plain-English test cases? They double as documentation. Always current. Always readable.
  • It works whether your team’s doing BDD, TDD, ADHD — whatever.

I use Cucumber on every team project where there’s even a hint of non-technical collaboration. It keeps everyone on the same page. Literally.

13. Headless Testing: Fast AF, But Sometimes a Little Blind

Want your tests to run faster? Run them headless. That means no browser window, no animations, no waiting for dumb cascading style sheets (CSS) transitions.

I use headless testing when:

  • I’m running oversized test suites across multiple browsers at once
  • I need fast feedback in CI/CD pipelines
  • I don’t care about what the UI looks like, just whether it works

Perks

  • Speed. Your tests fly without the browser needing to draw stuff on screen.
  • Scale. You can run 20 tests in parallel and your machine won’t melt.
  • Screenshots & perf tests work fine too you just won’t see anything while it runs.
  • Saves money when testing on cloud services (especially mobile emulators).

But here’s the rub

  • You’ll miss visual bugs. No hover issues, layout glitches, or misaligned buttons will be obvious.
  • Debugging sucks. When it fails, you get… nothing. No UI. No clues. Like trying to fix a toaster blindfolded.
  • Some JavaScript-heavy pages (I’m looking at you, React + animations) get weird in headless mode.
  • Compatibility varies, especially with older browsers or WebDriver quirks.

I love headless for speed, but I never trust it with final UI sign-off. If something looks wrong, you still need a real browser to catch it.

14. Taming Moving Targets: Dealing with Dynamic Tables Without Losing Your Mind

You ever try to test a table that changes every time you blink? Rows disappear. Columns morph. IDs? Yeah, those went out the window. Testing this kind of chaos isn’t just annoying it’s a trap. And I’ve been there. Mid-interview, thinking I had it under control, then boom the DOM changed, and my script bled out. Here’s how I stopped getting wrecked by these shapeshifting messes.

Let’s be real. Most tables on the web are lazy. No proper IDs. No helpful class names. They change with filters, pagination, or just because someone thought infinite scroll was “cool.”

  • Locators? Good luck. You’re not getting a neat id="table-row-1" you're getting a bunch of div soup.
  • Pagination? Now you’re stuck writing a loop that clicks through 17 pages just to find “John Doe.”
  • Sorting? Changes the entire DOM. Your script thinks it’s looking at row 3 turns out that’s someone else now.
  • Filtering? Might as well start over.
  • Extracting data? Ever tried pulling nested info from inside a table-within-a-table? It’s gross.

What Actually Works (Learned the Hard Way)

I’m not going to tell you to “use best practices.” I’ll just tell you what’s saved my ass more than once.

  • Forget IDs. Use Relationships.: Use XPath or CSS selectors based on how elements relate to each other like, “this cell under the 3rd header in this row.” Don’t get fancy. Just get specific.
  • Prep Your Test Data Like You’re Prepping For A Heist: Know precisely what you expect to see in the table. If your test data says “Alice” should be in row 4, then check for that. Don’t just hope she shows up somewhere.
  • Stop rushing. Wait for things: Dynamic tables love flickering between loading states. Use WebDriverWait. Wait for a row count. Wait for a specific value. Just… wait.
  • JavaScript = your sidekick: When Selenium gets dumb, use JS to yank the data directly. Sometimes that’s the only way to make sense of the madness.
  • Use Real Tools Made By People Who Suffered Before You: Stuff like robotframework-table or TableAU exists because someone out there also wanted to scream into a pillow after 8 hours of flaky tests. Use them.
  • Switch Frames Before You Start Poking Things: If the table’s inside a frame or an iframe, switch context. Otherwise, you're punching air.

15. Capture Evidence: How I Actually Take Screenshots in Selenium (Java)

I still remember bombing a test round years ago just because I couldn’t figure out how to attach a screenshot to a failing test. Embarrassing? Yup. Avoidable? Also yup.

Here’s how I fixed that.

The Straightforward Way TakesScreenshot

Look, you don’t need a fancy library. Java's TakesScreenshot interface gets the job done most of the time.

import org.openqa.selenium.OutputType;

import org.openqa.selenium.TakesScreenshot;

import org.openqa.selenium.WebDriver;

public class ScreenshotExample {

public static void main(String[] args) throws Exception {

WebDriver driver = ...; // Your usual setup

driver.get("https://www.example.com/");

// Take screenshot as bytes

TakesScreenshot screenshot = (TakesScreenshot) driver;

byte[] screenshotBytes = screenshot.getScreenshotAs(OutputType.BYTES);

// Save it (Apache Commons IO can help here)

FileUtils.writeByteArrayToFile(new File("screenshot.png"), screenshotBytes);

driver.quit();

}

}

It’s minimal. It works. And it saves your sanity when a bug decides to show up at 3 AM.

Other Stuff That’s Occasionally Useful

  • Apache Commons IO: Just makes saving files easier. Think of it as less typing and fewer null pointer surprises.
  • SikuliX: If your test needs to “see” the screen like a human (think image-matching), this one can help. Not always necessary. But handy when DOM isn’t your friend.
  • Manual Screenshots: Yeah, using DevTools for debugging can work. But don’t rely on it for automation. You’ll hate yourself later.

16. Data-Driven Design: The Only Way I Keep My Tests From Becoming a Mess

I used to hardcode every input like an absolute rookie. Felt productive… until I had to update 23 test files just to change a phone number.

If your test data is baked into your script, you’re doing too much work. Here’s a better way.

Why I Switched to Data-Driven Testing

  • Write once, test forever: One script. Ten different datasets. Boom10 tests.
  • Catch weird bugs early: Your edge cases are probably sitting in that CSV file you never used. Stop skipping them.
  • Quick edits: Want to change an input? Update the data file. Don’t touch the script.
  • Readable for humans: Test logic stays clean. Anyone reading it won't want to strangle you.
  • Easy to share: Teams love this. Especially when half your coworkers are still figuring out Git.

How I Actually Do It

  • Pick a data source: Excel, CSV, Google Sheets, or even a DB if you’re feeling spicy.
  • Read it in the test: Use Java to grab the row, loop through, and feed the inputs into your test like it's a buffet.
  • Compare expected vs actual: Your data file should also include anticipated results. Match them up after test runs.

Here's a dead-simple idea of how that looks:

@Test(dataProvider = "getData")

public void testLogin(String username, String password) {

// Fill form with data

loginPage.login(username, password);

// Check for expected result

Assert.assertEquals(homePage.getTitle(), "Dashboard");

}

Once I figured this out, I spent less time copy-pasting and more time actually fixing bugs. Which, let’s be real, is what gets you hired.

17. The Locator Map: Stop Copy-Pasting the Same Locators Everywhere Like It’s 2015

I’ll be honest when I first started with Selenium, I had locators sprinkled everywhere like hot sauce on bad takeout. XPath here, CSS selector there, everything hardcoded inside the test. Looked fine at first. Then the UI changed... and all my tests broke like cheap IKEA furniture.

That’s when I figured out I needed an Object Repository.

Here’s the plain version:

  • You store all your element locators in one central place.
  • When the website changes, you just update the locator once.
  • Your tests keep running without needing to rewrite half your code.

Think of it like having a contact list instead of memorizing phone numbers. Want to text your friend? You don’t guess their number every time. You open the app, tap their name. Same deal here.

Why It’s Worth Using

  • Fix it once: Button ID changed? Cool. Fix it in one file. Done.
  • Shareable: Use the same locator across different tests. Stop repeating yourself.
  • Cleaner code: Your tests stay readable. Your future self will thank you.
  • Flexible search: Try different locator strategies (ID, name, XPath) and see what sticks.

This one change saved me hours during interview prep. I wasn’t stuck debugging locator issues. I was solving real problems. The kind FAANG interviews throw at you.

If you're still hardcoding selectors inside your test logic, that’s your sign to stop. Build a locator map. Make your life easier.

18. Hover and interact: How I stopped fighting with mouse hover in Java Selenium

Alright, I’ll be honest with you. Hover actions in Selenium are a pain. You think it's going to be a simple “move here, click there” situation. Nah. It ghosts your commands like a recruiter on Friday afternoon.

I’ve banged my head on this enough times during interviews that I now just default to two ways: the Actions class (when things behave) and JavaScript (when they don’t).

Let’s go through both like someone who doesn’t have 12 hours to debug invisible submenus.

Option 1: When Selenium Actually Behaves:Actions Class

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.interactions.Actions;

public class HoverAndClickExample {

public static void main(String[] args) {

System.setProperty("webdriver.chrome.driver", "path/to/chromedriver.exe");

WebDriver driver = new ChromeDriver();

try {

driver.get("https://www.example.com/");

WebElement elementToHover = driver.findElement(By.id("hoverElement"));

Actions actions = new Actions(driver);

actions.moveToElement(elementToHover).perform();

Thread.sleep(1000); // I know, I know — but sometimes you need it.

actions.click(driver.findElement(By.xpath("//li[text()='SubMenu Item']"))).perform();

} catch (InterruptedException e) {

e.printStackTrace();

} finally {

driver.quit();

}

}

}

Why this works

You're telling Selenium to move the mouse like a human would literally. The .perform() part? That’s you saying, “Yes, actually do the thing now.” Without it, nothing happens. Ask me how I learned that the hard way.

Option 2: When The Page Says ‘No’ — JavaScript To The Rescue

import org.openqa.selenium.By;

import org.openqa.selenium.JavascriptExecutor;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

public class HoverExample {

public static void main(String[] args) {

System.setProperty("webdriver.chrome.driver", "path/to/chromedriver.exe");

WebDriver driver = new ChromeDriver();

try {

driver.get("https://www.example.com/");

WebElement elementToHover = driver.findElement(By.id("hoverElement"));

JavascriptExecutor js = (JavascriptExecutor) driver;

js.executeScript("arguments[0].dispatchEvent(new MouseEvent('mouseover'));", elementToHover);

} finally {

driver.quit();

}

}

}

Why You’d Use This

Sometimes, Selenium just refuses to trigger hover states like when the DOM is playing hard to get. JavaScript fakes it by dispatching a 'mouseover' event directly. Dirty, but effective.

Related Reading

Nail Coding Interviews with our AI Interview Assistant − Get Your Dream Job Today

I used to measure progress by how many LeetCode problems I could finish before passing out. It felt productive until I realized I couldn’t recall half of them during real interviews. What mattered wasn’t how many questions I solved, but how well I could think through a problem live and explain my code under pressure. That’s why I built Interview Coder not another problem bank, but a quiet training partner that keeps you focused on how you solve, not just how many you solve.

How Interview Coder Actually Works When You’re in the Hot Seat

Consider you’re mid‑interview, writing a function, and your brain blanks on the edge case logic. Interview Coder listens to your coding context and quietly drops hints, clean snippets, test ideas, and even quick reminders on data structures like HashMap or PriorityQueue. It’s not doing the work for you; it’s that friend sitting next to you saying, “Hey, you forgot to check for null input.” It helps you code faster, stay calm, and show the kind of clarity hiring managers actually care about.

Invisible During Screen Shares (Yeah, Really)

This one freaks people out until they see it Interview Coder never shows up on screen shares. Your IDE looks untouched. Everything happens quietly off‑screen, so you stay in control and focused.

It means you can explain your thought process, talk through trade‑offs, and still get that subtle nudge when you need it. No pop‑ups. No awkward pauses. Just you, coding like a pro while the assistant keeps things smooth behind the curtain.

Prepping for Java Selenium Interviews Without Losing Your Mind

If you’ve ever sat through a Selenium round, you know it’s never “just Java.” You’re juggling WebDriver setup, selectors, waits, and random edge cases that love breaking right before you demo.

Interview Coder gives you ready examples for stuff like XPath vs. CSS selectors, handling multiple windows, managing waits with WebDriverWait, or dealing with nightmares like StaleElementReferenceException.

It even walks you through Page Object Models, using Select for dropdowns, Actions for mouse events, and setting up Selenium Grid for cross‑browser tests. Basically, the tedious setup work gets out of your way so you can focus on showing what you actually know.

Java Selenium Interview Questions That Actually Come Up

Let me make this simple: if you're walking into a Java Selenium interview without knowing how to choose the right locator, wait properly, or structure your test setup, you're gonna feel it. Hard.

I’ve been grilled on everything from CSS vs. XPath to how you’d upload a file without clicking through the UI. People love asking about implicit v.s explicit waits and no, just saying “explicit is better” won’t cut it. You’ll get questions about how to use TestNG or JUnit annotations, how to take screenshots when tests fail, and whether you can set up DesiredCapabilities without Googling it mid-interview.

That’s why I built Interview Coder to give you fast, no-BS answers and sample code you can literally copy into your IDE none of that long-winded “theoretically speaking” stuff. You either know it or you don’t.

Debugging Isn’t About Guessing. It’s About Staying Calm.

Here’s the thing interviewers won’t say out loud: they’re watching your face when a test fails.

Are you scrambling? Or do you pause, look at the DOM, maybe drop in a quick console.log() or Selenium print, and walk them through what’s likely going wrong?

I used to spiral when things broke. Now, I just open up Interview Coder, replay the bug, and get clear on whether it’s timing, selectors, or just a bad assumption. It’ll even give you code snippets for retries, exception handling, and clean logging stuff that shows you actually think before typing.

You Decide What It Sees. Period.

Some tools act like you work for them. Interview Coder isn’t one of them.

You’re in complete control. Turn it on, turn it off. Limit what context it sees. Your sessions are encrypted, and if you want to double-check what happened during your mocks, audit logs have your back.

It’s built for real-life prep, not weird surveillance vibes.

You Need Examples That Actually Work in Interviews

Most tutorials show you a “login page test” and call it a day. That’s useless when you’re in a live coding round and someone says, “Can you use XPath axes to grab the third row’s checkbox only if column two says ‘Active’?”

Interview Coder doesn’t just show you what a Page Object Model looks like; it gives you ready-to-go examples of:

  • findElement variations
  • Select usage for dropdowns.
  • How to run your tests headless
  • Stubs for integrating with CI
  • Snippets for fluent waits that don’t make your tests flake out

This is the kind of stuff I practiced before I got my TikTok interview, and yeah, they noticed.

Why I Don’t Shut Up About This Tool

87,000+ engineers use it, but this isn’t some influencer stat. I made Interview Coder because I was tired of bombing interviews that I actually studied for. I wasn’t bad at coding. I was bad at explaining while coding. Once I started using Interview Coder, I stopped guessing and started talking through my process. That’s what recruiters want. Not “perfect” just clear, clean, and calm.

Got my first Amazon internship 4 weeks later.

What You Can Do Right Now

Skip the fluff. Download Interview Coder. Run a mock. Try solving:

  • A Selenium challenge with a flaky button
  • An implicit vs explicit wait scenario
  • A test that runs in CI and fails silently, and fix it

This isn’t homework. It’s a shortcut to the version of you that walks into interviews and actually enjoys them.

Interview Coder - AI Interview Assistant Logo

Ready to Pass Any SWE Interviews with 100% Undetectable AI?

Start Your Free Trial Today