如何使用Selenium验证页面标题?附登录场景测试代码示例
Complete Selenium Implementation to Verify Page Title After Login
Here's a polished, working solution using Selenium and TestNG to verify your homepage title after successful login, building directly on your provided code snippets:
Full Code Implementation
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class LoginTitleVerificationTest { private WebDriver driver; // Replace with your actual application base URL private String baseUrl = "https://your-application-url.com"; @BeforeMethod public void setUp() { // Initialize ChromeDriver (ensure ChromeDriver is in your system path or specify its location) driver = new ChromeDriver(); driver.manage().window().maximize(); } @Test(priority = 0) public void performLogin() throws Exception { driver.get(baseUrl + "/"); // Enter email and password driver.findElement(By.name("email")).clear(); driver.findElement(By.name("email")).sendKeys("lanka@ensiz.com"); driver.findElement(By.name("password")).clear(); driver.findElement(By.name("password")).sendKeys("123456"); // Click Sign In button driver.findElement(By.xpath("//button[contains(text(),'Sign In')]")).click(); // Optional: Use explicit wait instead of sleep for better reliability // WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); // wait.until(ExpectedConditions.titleContains("Placer Admin")); } @Test(priority = 1, dependsOnMethods = "performLogin") public void verifyHomepageTitle() { String expectedTitle = "Placer Admin - Home"; String actualTitle = driver.getTitle(); // Assert that the actual title matches the expected value Assert.assertEquals(actualTitle, expectedTitle, String.format("Homepage title mismatch: Expected '%s', got '%s'", expectedTitle, actualTitle)); } @AfterMethod public void tearDown() { // Clean up resources after each test if (driver != null) { driver.quit(); } } }
Key Details & Best Practices
- Test Dependencies: Using
dependsOnMethods = "performLogin"ensures the title verification only runs if the login is successful, which is more robust than relying solely onpriority. - Assertions: The
Assert.assertEqualsmethod provides a clear error message if the title doesn't match, making debugging easier. - Explicit Waits: Instead of hardcoding
Thread.sleep, use explicit waits (commented in the code) to wait for the title to update or elements to load. This makes your tests more stable and less flaky. - Resource Management: The
@AfterMethodannotation ensures the browser is closed after each test, preventing resource leaks.
内容的提问来源于stack exchange,提问作者user3806999
相关产品推荐
相关产品推荐

