Before writing the script, ensure you have:
- Java installed (JDK 11 or above)
- Maven or Gradle project setup
- Playwright for Java dependency added
Add maven dependency in pom.xml
:
<dependencies>
<dependency>
<groupId>com.microsoft.playwright</groupId>
<artifactId>playwright</artifactId>
<version>1.44.0</version>
</dependency>
</dependencies>
Java Code to Automate Login
import com.microsoft.playwright.*;
public class OrangeHRMLoginTest {
public static void main(String[] args) {
// Step 1: Launch Playwright
try (Playwright playwright = Playwright.create()) {
// Step 2: Launch a browser (Chromium)
Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));
// Step 3: Create a new browser context
BrowserContext context = browser.newContext();
// Step 4: Open a new page
Page page = context.newPage();
// Step 5: Navigate to the login page
page.navigate("https://opensource-demo.orangehrmlive.com/web/index.php/auth/login");
// Step 6: Wait for username input field to be visible
page.waitForSelector("input[name='username']");
// Step 7: Fill in the login credentials
page.fill("input[name='username']", "Admin");
page.fill("input[name='password']", "admin123");
// Step 8: Click the login button
page.click("button[type='submit']");
// Step 9: Print login success message
System.out.println("Login successful!");
// Optional: Close browser after verification
browser.close();
}
}
}
Code Explanation:
Line/Block | Explanation |
---|---|
Playwright.create() | Starts Playwright engine |
chromium().launch(...) | Launches Chromium browser (can be firefox() or webkit() too) |
browser.newContext() | Creates a new isolated browser context (like incognito) |
context.newPage() | Opens a new browser tab/page |
page.navigate(url) | Opens the specified URL |
page.fill(selector, value) | Enters value into input field (selector is a CSS locator) |
page.click(selector) | Clicks the element (e.g., login button) |
browser.close() | Closes the browser at the end |
Required Credentials
For this demo:
Username:
Admin
Password:
admin123
Points to Consider:
- This script assumes that the page loads fast enough, but for real-world tests, you should use explicit waits where needed.
- You can run this from a main method or integrate it into a test framework like JUnit/TestNG for proper test cases.
No comments:
Post a Comment