To automate a web-form login with Selenium and Java, open the login page, enter test credentials, submit the form, wait for an application-specific success or error state, and assert that state with a Java test framework such as JUnit. Use a dedicated test account and always close the browser session, including when a test fails.
How do I automate login testing with Selenium and Java?
This example tests an ordinary HTML login form. It uses JUnit 5 for the test lifecycle and assertions, Selenium WebDriver to control Chrome, and an explicit wait for the application’s signed-in indicator. The selectors and expected result are examples: replace them with selectors and behavior from the application you are testing.
Set these environment variables before running the test:
BASE_URL: the base URL of a local demo or staging application, such ashttps://staging.example.test.TEST_USERNAMEandTEST_PASSWORD: credentials for a dedicated test account. Do not put real credentials in source code or commit them to version control.
The project needs Selenium’s Java binding and JUnit Jupiter on its test classpath. Configure the build tool to use those dependencies and a Java version supported by the Selenium release you select. The example assumes Chrome is installed and that the project’s Selenium setup can provide a compatible driver.
Outdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchWindows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstall#1 Best Overall
- Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
- Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
- Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
- Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
- 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
Successful-login test
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.time.Duration;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
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.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
class LoginTest {
private WebDriver driver;
@BeforeEach
void setUp() {
driver = new ChromeDriver();
}
@AfterEach
void tearDown() {
if (driver != null) {
driver.quit();
}
}
@Test
void validCredentialsShowSignedInState() {
String baseUrl = requiredEnv("BASE_URL");
String username = requiredEnv("TEST_USERNAME");
String password = requiredEnv("TEST_PASSWORD");
driver.get(baseUrl + "/login");
driver.findElement(By.id("username")).sendKeys(username);
driver.findElement(By.id("password")).sendKeys(password);
driver.findElement(By.cssSelector("button[type='submit']")).click();
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement signedIn = wait.until(
ExpectedConditions.visibilityOfElementLocated(By.id("signed-in-indicator")));
assertTrue(signedIn.isDisplayed(), "Expected the signed-in indicator to be visible");
}
private static String requiredEnv(String name) {
String value = System.getenv(name);
if (value == null || value.isBlank()) {
throw new IllegalStateException("Set the " + name + " environment variable");
}
return value;
}
}
Run this class through your project’s JUnit test runner. The setup creates a fresh browser session for each test; teardown calls quit() after the test, even if an assertion or interaction fails. quit() ends the WebDriver session rather than merely closing one tab.
Adapt the selectors to the page
Use stable selectors owned by the application, such as IDs or dedicated test attributes. The example assumes fields with IDs username and password, a submit button matching button[type='submit'], and a post-login element with ID signed-in-indicator. If the page uses different markup, update the locators. Avoid relying on visible wording or layout selectors that may change for styling reasons unless those are the behavior you intend to test.
Rank #2
- 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
- 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
- Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
- 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
- What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
Test both accepted and rejected credentials
A click returning successfully does not prove that login worked. Assert an observable application outcome. Where the test environment supports both cases, keep successful and rejected login scenarios separate so each has a clear expected state.
| Case | Credentials | Wait for | Assert |
|---|---|---|---|
| Accepted login | A dedicated valid test account | A visible authenticated-state element, or another stable post-login condition | The authenticated state is present |
| Rejected login | A deliberately invalid test credential supported by the test environment | The application’s visible login error | The error state or expected message is present |
For a rejection test, use the same setup and teardown pattern, submit the invalid test values, and wait for the page’s actual error element. Do not assume every application redirects after success or uses the same error banner. Avoid repeatedly sending failed logins to a production service; use a local demo or staging environment intended for automation.
Do these 3 things before closing this tab:
1Scan for outdated or missing drivers - takes under a minute2Clear out junk files and repair common Windows errors3Fix the driver behind crashes, sound loss and screen glitchesWhy use an explicit wait for the result?
A navigation reaching its configured page-load readiness state does not necessarily mean client-side code has finished rendering or updating the login result. The next command can race an asynchronous page change, making a test flaky. An explicit wait polls for the particular condition the test needs—in this case, visibility of the signed-in indicator—and fails with a timeout if that condition does not arrive in the allotted time.
Rank #3
- Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
- Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
- Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
- Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
- What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
Avoid using a fixed sleep as the main synchronization strategy: it can waste time when the page responds quickly and still be too short when it responds slowly. Selenium also warns against mixing implicit and explicit waits because the resulting timeout behavior can be unpredictable. For this example, use the explicit condition-based wait and do not add a global implicit wait.
What Selenium and JUnit each do
WebDriver is the browser-driving interface: it navigates, locates elements, types, and clicks. It does not supply the test’s pass/fail comparisons or reporting. JUnit provides the test runner, lifecycle hooks, and assertion used here. This separation makes the browser actions and the expected application behavior explicit.
Rank #4
- Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
- Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
- Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
- Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
- Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
Form login is not HTTP authentication
This tutorial covers a page with username and password form fields. HTTP Basic or Digest authentication is a different mechanism and does not follow the same form-submission workflow. Selenium maintainer Simon Stewart’s 2021 discussion of Selenium 4 described a CDP-based approach for credentials as implementation-specific and tied to browser protocol support at that time; do not treat it as a universal current recipe. Check current Selenium and browser support if you need to automate HTTP authentication.
Troubleshooting common failures
Element not found
- Confirm that the browser opened the expected login URL and that the form has finished rendering.
- Inspect the page DOM and update the example locators to match the application’s actual IDs, attributes, or structure.
- If the form is inside an iframe, the test must switch to that frame before locating its elements.
The wait times out after submitting
- Check whether the application displayed an error instead of accepting the credentials.
- Inspect the current URL and DOM to determine whether the expected element changed, is hidden, or has a different selector.
- Verify the staging environment and test account before increasing the timeout. A longer wait will not fix a wrong selector, rejected credential, or failed page load.
Credentials are missing
The example deliberately fails with a clear message if a required environment variable is unset or blank. Set BASE_URL, TEST_USERNAME, and TEST_PASSWORD in the test process environment or your test configuration; do not replace them with committed secrets.
Best Value
- 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
- Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
- Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
- HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
- What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
Browser session does not close
Keep cleanup in JUnit’s @AfterEach hook and call driver.quit(). If browser startup fails, check that Chrome is installed and that the driver setup can obtain a compatible driver for the installed browser.
Or skip the browser setup
ScreenshotNeo is a website screenshot API, not a replacement for a Selenium functional login test: a screenshot alone cannot prove that credentials were accepted. It can help capture a page for a visual check. Its API returns an image or PDF from one GET request, and its options include waiting for a selector or network idle. See the ScreenshotNeo website and API documentation.
Quick Recap
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
Before a capture, ScreenshotNeo accepts cookie or consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and responses identify the page verdict and billing status in headers. An MCP server provides take_screenshot, get_page_info, and capture_pdf tools for AI agents. The free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots. Sign up free for 1,000 screenshots a month with no card.
Quick wins for a faster PC:
Scan for outdated or missing drivers - takes under a minuteDriver Scan →Repair Windows errors before they cause bigger problemsFix Now →Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

