0
0
Selenium Javatesting~10 mins

findElements for multiple matches in Selenium Java - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test opens a webpage and uses findElements to locate multiple buttons with the same class. It verifies that the correct number of buttons is found and that each button is displayed.

Test Code - JUnit
Selenium Java
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;

public class MultipleButtonsTest {
    WebDriver driver;

    @BeforeEach
    public void setUp() {
        driver = new ChromeDriver();
        driver.get("https://example.com/buttons");
    }

    @Test
    public void testFindMultipleButtons() {
        List<WebElement> buttons = driver.findElements(By.className("btn-primary"));
        assertFalse(buttons.isEmpty(), "No buttons found with class 'btn-primary'");
        assertEquals(3, buttons.size(), "Expected exactly 3 buttons with class 'btn-primary'");
        for (WebElement button : buttons) {
            assertTrue(button.isDisplayed(), "Button should be visible");
        }
    }

    @AfterEach
    public void tearDown() {
        if (driver != null) {
            driver.quit();
        }
    }
}
Execution Trace - 6 Steps
StepActionSystem StateAssertionResult
1Test starts and Chrome browser opensBrowser window is open, ready to navigate-PASS
2Browser navigates to https://example.com/buttonsPage with multiple buttons having class 'btn-primary' is loaded-PASS
3Find all elements with class name 'btn-primary' using findElementsList of WebElements representing buttons is retrievedVerify list is not emptyPASS
4Assert that exactly 3 buttons are foundList size is checkedbuttons.size() == 3PASS
5For each button found, check if it is displayedEach button element is visible on the pagebutton.isDisplayed() == true for all buttonsPASS
6Test ends and browser closesBrowser window is closed-PASS
Failure Scenario
Failing Condition: No elements found with class 'btn-primary' or number of elements is not 3
Execution Trace Quiz - 3 Questions
Test your understanding
What does the findElements method return if no matching elements are found?
ANull
BThrows NoSuchElementException
CAn empty list
DReturns the first element only
Key Result
Using findElements returns a list of all matching elements, allowing tests to verify multiple elements at once without failing if none are found. Always check the list size and visibility to ensure correct elements are present.