Selenium(Java)验证5次失败登录后账户锁定的测试方法
Got it, here's a robust Selenium Java test case that covers your account lockout requirement. I've included best practices like explicit waits to avoid flaky tests and structured the code for maintainability:
Selenium Java Test Case for Account Lockout After 5 Failed Login Attempts
Test Overview
This test will:
- Execute 5 consecutive failed login attempts with invalid credentials, verifying the error message each time.
- Attempt a login with valid credentials on the 6th try to confirm the account is locked for 30 minutes.
Full Test Code
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 org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.time.Duration; public class LoginLockoutTest { private WebDriver driver; private WebDriverWait wait; // Update these constants to match your website's elements and URLs private static final String LOGIN_PAGE_URL = "https://your-website-login-url.com"; private static final By USERNAME_INPUT = By.id("username"); // Adjust locator (ID, XPath, etc.) private static final By PASSWORD_INPUT = By.id("password"); private static final By LOGIN_SUBMIT_BTN = By.cssSelector("button[type='submit']"); private static final By INVALID_CRED_ERROR = By.xpath("//div[text()='Invalid username or password combination']"); private static final By ACCOUNT_LOCKED_ALERT = By.xpath("//div[contains(text(), 'Account locked for 30 minutes')]"); // Test credentials (replace with valid test data) private static final String VALID_USER = "test_user_123"; private static final String VALID_PASS = "SecurePass123!"; private static final String INVALID_PASS = "WrongPass456!"; @BeforeMethod public void setupTest() { // Initialize ChromeDriver (ensure ChromeDriver is in your PATH or set via System.setProperty) driver = new ChromeDriver(); driver.manage().window().maximize(); // 10-second explicit wait for element interactions wait = new WebDriverWait(driver, Duration.ofSeconds(10)); driver.get(LOGIN_PAGE_URL); } @Test public void verifyAccountLockoutAfter5FailedAttempts() { // Step 1: Perform 5 failed login attempts for (int attemptNum = 1; attemptNum <= 5; attemptNum++) { submitLoginForm(VALID_USER, INVALID_PASS); // Verify error message appears after each failed attempt WebElement errorMessage = wait.until(ExpectedConditions.visibilityOfElementLocated(INVALID_CRED_ERROR)); assert errorMessage.isDisplayed() : "Error message missing after failed attempt #" + attemptNum; System.out.println("Failed attempt #" + attemptNum + ": Error message confirmed"); // Refresh login page for next attempt (adjust if your site handles this differently) driver.navigate().refresh(); } // Step 2: Attempt login with valid credentials post-lockout submitLoginForm(VALID_USER, VALID_PASS); // Step 3: Verify account locked message is displayed WebElement lockedMessage = wait.until(ExpectedConditions.visibilityOfElementLocated(ACCOUNT_LOCKED_ALERT)); assert lockedMessage.isDisplayed() : "Account locked message not shown after 5 failed attempts"; System.out.println("Success: Account locked as expected after 5 failed login attempts"); } /** * Helper method to fill and submit the login form */ private void submitLoginForm(String username, String password) { // Wait for username field to be interactive, then enter credentials WebElement usernameField = wait.until(ExpectedConditions.elementToBeClickable(USERNAME_INPUT)); usernameField.clear(); usernameField.sendKeys(username); WebElement passwordField = wait.until(ExpectedConditions.elementToBeClickable(PASSWORD_INPUT)); passwordField.clear(); passwordField.sendKeys(password); // Submit the form WebElement loginBtn = wait.until(ExpectedConditions.elementToBeClickable(LOGIN_SUBMIT_BTN)); loginBtn.click(); } @AfterMethod public void cleanupTest() { // Close the browser after test completion if (driver != null) { driver.quit(); } } }
Important Notes for Implementation:
- Locator Adjustments: Use your browser's dev tools (F12) to inspect elements and update the locators (IDs, XPaths, CSS selectors) to match your website's actual HTML.
- Dependencies: Add these to your Maven
pom.xml(or equivalent for Gradle) to include Selenium and TestNG:<dependencies> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>4.15.0</version> <!-- Use the latest stable version --> </dependency> <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>7.8.0</version> <scope>test</scope> </dependency> </dependencies> - Test Data: Replace the credential constants with valid test users from your system.
- Page Behavior: If your login page doesn't require a refresh after failed attempts, modify the loop to clear the input fields instead of refreshing.
- Lockout Duration Testing: To verify the account unlocks after 30 minutes, you'd need to either wait (not ideal for test speed) or use an admin API to reset the lockout state for subsequent tests.
内容的提问来源于stack exchange,提问作者kritika agarwal
相关产品推荐
相关产品推荐

