0
0
Selenium Javatesting~10 mins

Logging with Log4j in Selenium Java - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test opens a web page using Selenium WebDriver and logs each step using Log4j. It verifies that the page title matches the expected title, demonstrating how logging helps track test execution.

Test Code - JUnit 5 with Selenium WebDriver and Log4j 2
Selenium Java
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import static org.junit.jupiter.api.Assertions.assertEquals;

public class LoggingWithLog4jTest {
    private static final Logger logger = LogManager.getLogger(LoggingWithLog4jTest.class);
    private WebDriver driver;

    @BeforeEach
    public void setUp() {
        logger.info("Setting up WebDriver");
        driver = new ChromeDriver();
        logger.info("WebDriver setup complete");
    }

    @Test
    public void testPageTitle() {
        logger.info("Starting test: testPageTitle");
        driver.get("https://example.com");
        logger.info("Navigated to https://example.com");

        String expectedTitle = "Example Domain";
        String actualTitle = driver.getTitle();
        logger.info("Page title retrieved: " + actualTitle);

        assertEquals(expectedTitle, actualTitle, "Page title should match expected");
        logger.info("Assertion passed: Page title matches expected");
    }

    @AfterEach
    public void tearDown() {
        logger.info("Closing WebDriver");
        if (driver != null) {
            driver.quit();
            logger.info("WebDriver closed");
        }
    }
}
Execution Trace - 5 Steps
StepActionSystem StateAssertionResult
1Initialize WebDriver and Log4j loggerLogger ready, WebDriver instance created but browser not opened-PASS
2Open browser and navigate to https://example.comBrowser window opened at https://example.com-PASS
3Retrieve page titlePage loaded with title 'Example Domain'Check if page title equals 'Example Domain'PASS
4Assert page title matches expectedPage title is 'Example Domain'assertEquals('Example Domain', actualTitle)PASS
5Close browser and quit WebDriverBrowser closed, WebDriver quit-PASS
Failure Scenario
Failing Condition: Page title does not match expected 'Example Domain'
Execution Trace Quiz - 3 Questions
Test your understanding
What does the logger record when the browser navigates to the URL?
ALogger records 'Navigated to https://example.com'
BLogger records 'Browser closed'
CLogger records 'Assertion passed'
DLogger records 'Setting up WebDriver'
Key Result
Logging each test step with Log4j helps track test progress and quickly identify where failures occur, improving debugging efficiency.