Friday, April 11, 2025

Questions: Playwright with java

Here's a carefully curated list of possible Playwright + Java interview questions, including:

  • ✅ Core Java (OOPs, exceptions, etc.)

  • ✅ Playwright automation

  • ✅ TestNG framework

  • ✅ BDD with Cucumber

  • ✅ Bonus: Code snippets, concepts, and real-life scenarios

Let’s go! 🔥


🚀 Playwright + Java Automation – Interview Q&A

1. What is Playwright and how is it different from Selenium?

Answer: Playwright is a modern automation library for web apps that supports multiple languages (Java, JavaScript, Python, etc.).
It supports:

  • Multiple browsers (Chromium, Firefox, WebKit)

  • Auto-waiting

  • Headless/headful mode

  • Native support for iframes, tabs, and download uploads

  • Built-in screenshot/video capabilities

📌 Unlike Selenium:

  • Playwright is faster and more reliable due to auto-waiting

  • Has native support for modern UI elements and multiple tabs


2. How do you launch a browser and open a page in Playwright Java?

Code Example:

Playwright playwright = Playwright.create();
Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));
Page page = browser.newPage();
page.navigate("https://example.com");

3. How do you locate elements in Playwright Java?

Answer:

  • page.locator("css selector")

  • page.getByText("Login")

  • page.getByRole(…)

📌 Example:

Locator loginBtn = page.locator("#login-button");
loginBtn.click();

4. How do you handle dropdowns in Playwright?

page.selectOption("#dropdown-id", new SelectOption().setLabel("Option 1"));

5. How to capture a screenshot?

page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("screenshot.png")));

🧪 TestNG + Playwright


6. How do you integrate Playwright with TestNG?

Answer: Create a base class with setup/teardown methods using @BeforeClass, @AfterClass, and write test methods using @Test.

Code Sample:

@BeforeClass
public void setup() {
    playwright = Playwright.create();
    browser = playwright.chromium().launch();
    page = browser.newPage();
}

@Test
public void testLogin() {
    page.navigate("https://example.com");
    page.fill("#username", "admin");
    page.fill("#password", "pass");
    page.click("#loginBtn");
}

7. How do you take a screenshot on failure in TestNG?

@AfterMethod
public void tearDown(ITestResult result) {
    if (ITestResult.FAILURE == result.getStatus()) {
        page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("screenshots/" + result.getName() + ".png")));
    }
}

🧾 Java + OOPs Interview Questions


8. Explain OOPs Concepts in Java (with real test example)?

Answer:

  • Encapsulation: Page classes hold locators and actions.

  • Inheritance: BaseTest class is extended by test classes.

  • Polymorphism: Method overloading in utility classes.

  • Abstraction: Interface for Page layer.


9. What’s the difference between ArrayList and LinkedList?

Answer:

  • ArrayList: Fast for retrieval, slower for inserts/removals

  • LinkedList: Faster for insertions/removals, slower for retrieval


10. What are checked vs unchecked exceptions?

Answer:

  • Checked: Caught at compile time (IOException)

  • Unchecked: Runtime exceptions (NullPointerException)


🧠 BDD with Cucumber + Java + Playwright


11. How do you implement BDD in Java with Playwright?

Answer:

  • Use Cucumber for BDD

  • Define .feature file

  • Use Step Definitions to map Gherkin steps to Playwright Java code


12. Sample Feature File

Feature: Login functionality

Scenario: Successful login
  Given I open the login page
  When I enter valid credentials
  Then I should see the homepage

13. Step Definition Example

@Given("I open the login page")
public void openLoginPage() {
    page.navigate("https://example.com/login");
}

14. How do you share Playwright context between steps?

Answer: Use a TestContext or Hooks class to store and share browser/page instances.


⚙️ Real-World Scenarios


15. How do you handle pop-ups or alerts?

page.onDialog(dialog -> {
    System.out.println("Alert Text: " + dialog.message());
    dialog.accept();
});

16. How do you handle multiple windows or tabs?

Page newPage = context.waitForPage(() -> {
    page.click("#open-new-tab");
});
newPage.bringToFront();

17. How do you wait for an element in Playwright?

page.waitForSelector("#element-id", new Page.WaitForSelectorOptions().setTimeout(5000));

18. How do you verify an element is visible and enabled?

boolean isVisible = page.locator("#submit").isVisible();
boolean isEnabled = page.locator("#submit").isEnabled();

19. Playwright’s default timeout? Can it be changed?

Default: 30 seconds
Override:

page.setDefaultTimeout(10000); // 10 seconds

20. Playwright test best practices

  • Use Page Object Model

  • Isolate test data

  • Use assertions wisely

  • Capture screenshots on failure

  • Avoid hard waits, use Playwright's auto-waiting


21. Please provide all the possible methods for page.


Navigation & Page Control
navigate(): page.navigate("https://example.com");
reload(): page.reload();
goBack(): page.goBack();
goForward(): page.goForward();
title(): String title = page.title();
url(): String url = page.url();
Element Interaction
click(): page.click("#login");
fill(): page.fill("#username", "admin");
type(): page.type("#search", "Playwright");
press(): page.press("#input", "Enter");
check(): page.check("#accept");
uncheck(): page.uncheck("#accept");
selectOption(): page.selectOption("#country", "India");
dblclick(): page.dblclick(".item");
hover(): page.hover("#menu");
Locators
locator(): Locator button = page.locator("#submit");
getByText(): page.getByText("Login");
getByRole(): page.getByRole(AriaRole.BUTTON);
Assertions and State
Playwright Java - Page Methods Cheat Sheet
isVisible(): page.locator("#msg").isVisible();
isEnabled(): page.locator("#submit").isEnabled();
isChecked(): page.locator("#accept").isChecked();
textContent(): page.locator(".info").textContent();
innerText(): page.locator("#header").innerText();
inputValue(): page.locator("#email").inputValue();
Waits and Synchronization
waitForSelector(): page.waitForSelector("#done");
waitForTimeout(): page.waitForTimeout(3000);
waitForLoadState(): page.waitForLoadState(LoadState.NETWORKIDLE);
waitForURL(): page.waitForURL("**/dashboard");
Screenshots & PDF
screenshot(): page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("shot.png")));
pdf(): page.pdf(new Page.PdfOptions().setPath(Paths.get("page.pdf")));
Frames and Popups
frame(): Frame frame = page.frame("myFrame");
waitForPopup(): Page popup = page.waitForPopup(() -> page.click("#link"));
File Upload & Download
setInputFiles(): page.setInputFiles("#file", Paths.get("data.txt"));
waitForDownload(): Download download = page.waitForDownload(() -> { page.click("#download-btn"); });
download.saveAs(Paths.get("myfile.zip"));
Dialogs / Alerts
onDialog(): page.onDialog(dialog -> {
Playwright Java - Page Methods Cheat Sheet
System.out.println(dialog.message());
dialog.accept();
});
Others
evaluate(): page.evaluate("() => alert('Hi')");
addInitScript(): page.addInitScript("console.log('Script added')");
close(): page.close();



22. Parallel execution with Playwright with java. 

1. TestNG Parallel Execution (Recommended)

Playwright + TestNG combo is super effective for parallel tests.

📌 Step-by-Step:

a. Update testng.xml to enable parallel test classes or methods:

xml
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd" > <suite name="Playwright Suite" parallel="classes" thread-count="3"> <test name="Tests"> <classes> <class name="tests.LoginTest"/> <class name="tests.SearchTest"/> </classes> </test> </suite>
  • parallel="classes": Runs each class in a separate thread

  • parallel="methods": Runs each test method in a separate thread

  • thread-count: Number of threads to run in parallel

b. Make sure your browser context is thread-safe:

Use ThreadLocal or independent instances of Playwright, Browser, and Page in each test.

🔐 Example (Thread-safe setup):

java
public class BaseTest { protected ThreadLocal<Playwright> playwright = new ThreadLocal<>(); protected ThreadLocal<Browser> browser = new ThreadLocal<>(); protected ThreadLocal<Page> page = new ThreadLocal<>(); @BeforeMethod public void setUp() { playwright.set(Playwright.create()); browser.set(playwright.get().chromium().launch()); page.set(browser.get().newPage()); } @AfterMethod public void tearDown() { page.get().close(); browser.get().close(); playwright.get().close(); } public Page getPage() { return page.get(); } }

Then in your test class, use:

java
@Test public void testLogin() { Page page = getPage(); page.navigate("https://example.com"); page.fill("#username", "admin"); page.click("#login"); }

✅ 2. Cucumber + TestNG Parallel Execution (Feature files in parallel)

  • Use the dataprovider + parallel option with Cucumber

  • Split scenarios across multiple threads

Want a full example with Cucumber + Playwright + TestNG parallel setup? Let me know!


✅ 3. Custom Java ExecutorService (Advanced)

You can manually create threads to execute different test classes or cases in parallel using Java’s ExecutorService.


22. Element locating techniques if you are using java and playwright.

Perfect — you're using Playwright with Java and want to know how to locate elements, including in complex scenarios like tables, nested elements, loops, and even Shadow DOM.

Let’s go step-by-step, from basic to advanced ⤵️


🔹 1. Basic Locators in Playwright Java

page.locator("#username").fill("admin");
page.locator(".btn-primary").click();
page.locator("input[name='email']").type("user@example.com");

✅ Supports CSS selectors, text selectors, and built-in queries.


🔹 2. Text Selectors

page.locator("text=Submit").click(); // Exact or partial match

🔹 3. Label Selectors

page.getByLabel("Email").fill("test@example.com");

🔹 4. Role Selectors (ARIA)

page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Login")).click();

🔹 5. Placeholder Selectors

page.getByPlaceholder("Enter your name").fill("John Doe");

🔹 6. Table Elements (Complex Table Lookups)

Assume this HTML:

<table>
  <tr>
    <td>Name</td>
    <td>Email</td>
  </tr>
  <tr>
    <td>John</td>
    <td>john@example.com</td>
  </tr>
</table>

📌 Locate by Cell Text:

Locator row = page.locator("table tr", new Locator.LocatorOptions().setHasText("John"));
String email = row.locator("td:nth-child(2)").textContent();
System.out.println("Email: " + email);

🔹 7. Nested Element (DOM Tree Traversal)

<div class="card">
  <div class="header">User Info</div>
  <div class="content">
    <span>Name:</span>
    <span>John Doe</span>
  </div>
</div>

📌 Java Locator:

Locator card = page.locator(".card", new Locator.LocatorOptions().setHasText("User Info"));
String name = card.locator(".content span:nth-of-type(2)").textContent();
System.out.println("Name: " + name);

🔹 8. Loop Over Multiple Elements (List/Repeater)

<ul>
  <li class="user">Alice</li>
  <li class="user">Bob</li>
  <li class="user">Charlie</li>
</ul>

📌 Java Code:

Locator users = page.locator("li.user");
int count = users.count();
for (int i = 0; i < count; i++) {
  System.out.println("User: " + users.nth(i).textContent());
}

🔹 9. Shadow DOM Handling

<custom-element>
  #shadow-root
    <input id="shadow-input" />
</custom-element>

📌 Java Code:

Playwright handles shadow DOM automatically when using locator():

page.locator("custom-element >> shadow=#shadow-input").fill("Inside Shadow DOM");

✅ The >> shadow= syntax pierces the shadow root.


🔹 10. Advanced Nested Table with Actions

<table>
  <tr>
    <td>John</td>
    <td><button>Edit</button></td>
  </tr>
</table>

📌 Click the "Edit" button for "John"

Locator row = page.locator("tr", new Locator.LocatorOptions().setHasText("John"));
row.locator("button").click();

🔹 BONUS: Combine Multiple Conditions

// Find a visible input with class and placeholder
page.locator("input.visible-input[placeholder='Search']:not([disabled])").fill("Playwright");

⚙️ Tools to Help

  • Use npx playwright codegen (even with Java!) to get a head start on selectors.

  • Use page.locator("selector").highlight() during debugging (JS only — in Java you can debug with .screenshot() or log outputs).


23. Any difference when you define lcoator when you use playwright with java or playwright with typescript?


Great question! 💡
Yes, there are some differences in how you define and use locators in Playwright when using Java vs. TypeScript, but the core concepts remain the same.


What's the Same?

Concept Java TypeScript
CSS selectors page.locator("div.class") page.locator("div.class")
Text selectors text=Login text=Login
Shadow DOM >> shadow= syntax >> shadow= syntax
Locator chaining .locator(...).locator(...) .locator(...).locator(...)
ARIA roles / semantic queries getByRole(...) getByRole(...)

The underlying selector engine and logic is the same.


🔀 What’s Different Between Java and TypeScript?

Here are the key differences 👇


1. Method Syntax / API Style

🔹 Java:

Locator button = page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Submit"));

🔹 TypeScript:

const button = page.getByRole('button', { name: 'Submit' });

✅ Same logic — Java is just more verbose due to types and method chaining.


2. Options & Locators

  • In Java, you explicitly create options classes like:

    new Locator.LocatorOptions().setHasText("User")
    
  • In TypeScript, you just pass a JS object:

    locator("tr", { hasText: "User" })
    

3. Asynchronous Handling

  • TypeScript is async — almost every Playwright action is awaited.

    await page.click('text=Login');
    
  • Java is synchronous-like — most methods block until complete.

    page.locator("text=Login").click();
    

But both do auto-waiting behind the scenes.


4. Code Completion & Language Features

  • TypeScript has more fluid intellisense for Playwright APIs.

  • Java needs more manual config (e.g., setting up Maven/Gradle and imports).

  • TypeScript can use playwright.config.ts to configure projects easily.


5. Test Runner Integration

Feature TypeScript Java
Built-in test runner @playwright/test ❌ (uses JUnit/TestNG manually)
Parallel testing ✅ native ✅ with test framework
Fixtures ✅ built-in ❌ (you create with setup/teardown)

🧪 Example Comparison: Fill Email Field

🟨 Java:

page.getByLabel("Email").fill("user@example.com");

🟦 TypeScript:

await page.getByLabel('Email').fill('user@example.com');

Same result — just different flavor.


🚀 Summary

Feature Java TypeScript
Verbose syntax ✅ Yes (OO-style) ❌ Shorter, cleaner
Async handling Blocking (sync-like) Async with await
Options/Configs Needs classes Just pass JS objects
Test runner Use JUnit/TestNG manually Built-in @playwright/test runner
Intellisense IDE-dependent Superb in VS Code


No comments:

Post a Comment