import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
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 java.time.Duration;
public class LoginTests {
private WebDriver driver;
private WebDriverWait wait;
private final String baseUrl = "https://example.com/login";
private final String dashboardUrl = "https://example.com/dashboard";
@BeforeEach
public void setUp() {
driver = new ChromeDriver();
wait = new WebDriverWait(driver, Duration.ofSeconds(10));
driver.get(baseUrl);
}
@Test
public void testLoginRedirectsToDashboard() {
driver.findElement(By.id("username")).sendKeys("testuser");
driver.findElement(By.id("password")).sendKeys("Password123!");
driver.findElement(By.id("login-button")).click();
wait.until(ExpectedConditions.urlToBe(dashboardUrl));
String currentUrl = driver.getCurrentUrl();
assertEquals(dashboardUrl, currentUrl, "URL should be dashboard after login");
driver.quit();
}
@Test
public void testWelcomeMessageDisplayed() {
driver.findElement(By.id("username")).sendKeys("testuser");
driver.findElement(By.id("password")).sendKeys("Password123!");
driver.findElement(By.id("login-button")).click();
wait.until(ExpectedConditions.urlToBe(dashboardUrl));
WebElement welcomeMessage = wait.until(
ExpectedConditions.visibilityOfElementLocated(By.id("welcome-msg")));
assertEquals("Welcome, testuser!", welcomeMessage.getText(), "Welcome message should greet the user");
driver.quit();
}
}The code uses JUnit 5 and Selenium WebDriver to automate the login test.
We have two test methods, each with a single assertion to keep tests focused and failures clear:
- testLoginRedirectsToDashboard checks that after login, the URL changes to the dashboard URL.
- testWelcomeMessageDisplayed checks that the welcome message text is correct after login.
Both tests share setup steps to open the login page and enter credentials.
Explicit waits ensure the page loads and elements appear before assertions.
Using one assertion per test helps isolate which feature failed if a test breaks.
Driver is closed after each test to avoid resource leaks.