Test groups in Selenium Java - Build an Automation Script
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.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.time.Duration; public class LoginTest { WebDriver driver; WebDriverWait wait; @BeforeClass public void setUp() { driver = new ChromeDriver(); wait = new WebDriverWait(driver, Duration.ofSeconds(10)); driver.manage().window().maximize(); } @Test(groups = {"smoke", "login"}) public void testValidLogin() { driver.get("https://example.com/login"); WebElement emailField = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("email"))); emailField.sendKeys("user@example.com"); WebElement passwordField = driver.findElement(By.id("password")); passwordField.sendKeys("Password123"); WebElement loginButton = wait.until(ExpectedConditions.elementToBeClickable(By.id("loginBtn"))); loginButton.click(); wait.until(ExpectedConditions.urlContains("/dashboard")); String currentUrl = driver.getCurrentUrl(); Assert.assertTrue(currentUrl.contains("/dashboard"), "User is not redirected to dashboard after login"); } @AfterClass public void tearDown() { if (driver != null) { driver.quit(); } } }
This test uses TestNG with Selenium WebDriver to automate the login test case.
Setup: The @BeforeClass method initializes the ChromeDriver and WebDriverWait for explicit waits.
Test method: The @Test annotation includes groups = {"smoke", "login"} to assign this test to two groups. This allows running tests selectively by group.
We open the login page, wait for the email field to be visible, enter the email and password, then wait until the login button is clickable before clicking it.
After clicking, we wait until the URL contains '/dashboard' to confirm navigation, then assert that the current URL is correct.
Teardown: The @AfterClass method closes the browser.
This structure follows best practices: explicit waits avoid flaky tests, grouping allows flexible test runs, and assertions verify expected outcomes.
Now add data-driven testing with 3 different sets of login credentials (valid and invalid)