To automate login testing with Selenium and Java, open the application’s login page, enter test credentials, submit the form, then wait for and assert an application-specific success or rejection state. Use a dedicated test account in a local demo or staging environment, keep credentials out of source control, and always close the browser—even when a test fails.
How do I automate login testing with Selenium and Java?
Selenium WebDriver drives the browser; it does not provide the test’s pass/fail assertions or reporting. Pair it with a Java test framework such as JUnit: WebDriver performs the browser actions, and JUnit checks whether the application reached the expected state. Selenium describes WebDriver as the browser automation interface, while its components guidance explains the separate role of test frameworks.
This example is for a conventional HTML login form. The selectors and post-login element are examples; replace them with stable IDs or test-specific attributes from your application. It uses a fresh Chrome session for each test and reads the base URL and credentials from environment variables.
Set up a Java test
In a Maven project, add Selenium Java and JUnit Jupiter as test dependencies. The version numbers below are illustrative; use versions approved for your project and compatible with your Java runtime.
Quick wins for a faster PC:
Repair Windows errors before they cause bigger problemsFix Now →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →#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.
<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>YOUR_SELENIUM_VERSION</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>YOUR_JUNIT_VERSION</version>
<scope>test</scope>
</dependency>
</dependencies>
Configure Maven Surefire to run JUnit 5 if your project’s existing Maven setup does not already support it. Selenium’s Java example shows the general setup, browser interaction, result check, and teardown pattern in its getting-started guide.
Write success and rejection tests
The tests below use explicit waits for visible application outcomes. Set BASE_URL, TEST_USERNAME, TEST_PASSWORD, INVALID_USERNAME, and INVALID_PASSWORD in the test environment. Use credentials created specifically for testing; do not commit real secrets into Java source or a repository.
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.
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;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
class LoginTest {
private WebDriver driver;
private WebDriverWait wait;
private String baseUrl;
@BeforeEach
void setUp() {
baseUrl = requiredEnv("BASE_URL");
driver = new ChromeDriver();
wait = new WebDriverWait(driver, Duration.ofSeconds(10));
}
@AfterEach
void tearDown() {
if (driver != null) {
driver.quit();
}
}
@Test
void validCredentialsReachSignedInState() {
openLoginAndSubmit(requiredEnv("TEST_USERNAME"), requiredEnv("TEST_PASSWORD"));
WebElement signedIn = wait.until(
ExpectedConditions.visibilityOfElementLocated(By.id("signed-in-indicator")));
assertTrue(signedIn.isDisplayed());
}
@Test
void invalidCredentialsShowRejection() {
openLoginAndSubmit(requiredEnv("INVALID_USERNAME"), requiredEnv("INVALID_PASSWORD"));
WebElement error = wait.until(
ExpectedConditions.visibilityOfElementLocated(By.id("login-error")));
assertEquals("Invalid username or password", error.getText().trim());
}
private void openLoginAndSubmit(String username, String 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();
}
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;
}
}
Change /login, the input and button selectors, the success element, and the exact error message to match the application. Some applications signal login success by showing a dashboard heading or account menu rather than a dedicated indicator; choose a stable condition that represents authenticated state. Likewise, the rejection case should assert the application’s actual error state, not assume a particular wording.
Choose the expected condition for each outcome
| Case | Test input | Wait for | Assert |
|---|---|---|---|
| Successful login | Dedicated valid test account | A visible signed-in indicator or another stable authenticated-state element | The element is visible, or another application-specific authenticated state holds |
| Rejected login | Credentials known to be invalid in the test environment | A visible login error element | The expected error text or rejection state |
A click returning successfully only proves that the browser command completed. It does not prove that login succeeded or failed. The application outcome is what the test should verify.
Free tools Windows power users keep installed
One-click scans. No signup required.
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.
Wait for the page’s real state
A navigation reaching its configured page-load readiness state does not guarantee that JavaScript has rendered or updated the login result. An immediate lookup after clicking can race an asynchronous update and make the test flaky. Selenium’s waiting strategies documentation describes explicit waits as polling for a specified condition until it succeeds or times out.
- Use an explicit wait for the specific condition your test needs, such as a visible success marker or error message.
- Avoid relying on a fixed sleep as the main synchronization method: it can waste time when the page is fast and still be too short when it is slow.
- Do not mix implicit and explicit waits. Selenium warns that doing so can produce unpredictable timeout behavior. Prefer the condition-based explicit wait shown here.
- Set the timeout to suit the test environment, and diagnose a missing condition before simply extending the timeout.
Run the test and diagnose failures
Run the test with your project’s normal Maven test command, for example mvn test. If a test times out, first identify which expected element did not appear and inspect the browser’s resulting URL and DOM. Verify the selector, test account, application state, and environment before changing the wait duration.
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
- Element not found before submission: The locator may not match the current page, or the form may not yet be rendered. Inspect the DOM and use a stable application-owned selector; if the form renders asynchronously, wait for the input to be present or visible before interacting.
- Success or error wait times out: Confirm that the test reached the intended environment and that the expected outcome is represented by the selector and condition you chose. Inspect the resulting URL and page DOM to see whether the application navigated, displayed a different message, or did not respond.
- Invalid-login test unexpectedly passes or fails: Check that the supplied account is actually invalid for this test environment and that the assertion matches the app’s rejection state. Avoid reusing a valid account for this case.
- Browser process remains after a failure: Keep driver shutdown in an
@AfterEachmethod or afinallyblock so cleanup runs when an assertion or browser action fails. - Credentials are missing: Supply the required environment variables in the test runner’s configuration. The helper in the example fails with the missing variable’s name rather than silently submitting empty credentials.
Form login is not HTTP authentication
This tutorial covers a page with username and password fields. HTTP Basic or Digest authentication is a different mechanism and should not be treated as a form-submission problem. In a 2021 article, Selenium maintainer Simon Stewart distinguished form-based login from Basic or Digest authentication, noting that the latter had historically been harder to handle. The article’s Selenium 4 register discussion was CDP-based and specific to browser support at that time; check current Selenium and browser documentation before relying on that approach. Read the historical authentication discussion.
Or skip the browser setup
If you need a screenshot of the login page or its resulting state for documentation or inspection, ScreenshotNeo can capture a URL with one GET request. This is not a replacement for Selenium’s interactive login test or its assertions; use Selenium to verify behavior and a screenshot capture when a visual artifact is what you need.
Quick Recap
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.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
Replace the target URL with the page you want to capture and supply an API key. See the ScreenshotNeo API documentation for request options. It removes cookie banners, newsletter popups, and chat widgets before capture; bot checks, blank pages, and failed loads are not billed. Its MCP server lets AI agents take screenshots, and the free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000. Learn about ScreenshotNeo or sign up for 1,000 free screenshots a month, with no card.
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.




