Verify user login and welcome message
Preconditions (2)
✅ Expected Result: User is logged in successfully, dashboard page is shown, and welcome message is displayed
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:
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.
Now add data-driven testing with 3 different username and password combinations to verify login success or failure.
sum(2, 3) returns 6?
@Test
void testSum() {
assertEquals(5, sum(2, 3));
}@Test
void testUser() {
assertEquals("John", user.getName());
assertEquals(30, user.getAge());
}calculateDiscount that returns a discount percentage based on user type and purchase amount. How should you write JUnit tests following the single assertion per test debate best practice?Pass the test and this pattern moves unknown