Hamburger Icon
  • Labs icon Lab
  • Core Tech
Labs

Guided: Playwright Foundations with Java

This hands-on code lab guides you through building end-to-end tests for a real website. You'll master core Playwright concepts like locating elements, simulating user actions, navigating between pages, and writing assertions to validate website behavior. Level up your testing skills and ensure flawless user experiences for any web application!

Labs

Path Info

Level
Clock icon Beginner
Duration
Clock icon 31m
Published
Clock icon Sep 09, 2024

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

Table of Contents

  1. Challenge

    Introduction and Set Up

    In this section, you'll set up the project and install the necessary dependencies that you need to run Playwright with Java.

    Playwright is a Java library that allows you to write end-to-end tests and automation for web applications.

    The Java file you will be working on throughout this guide is src/main/java/com/pluralsight/App.java.

    To run the application code at any time, execute:

    mvn clean compile exec:java -Dexec.mainClass="com.pluralsight.App" -Dexec.classpathScope=runtime
    

    And if you need some help, or want to see the working solution code, you can view the src/main/java/com/pluralsight/Solution.java file.

    You will be testing a locally hosted web application that you can view in the Web page tab (second tab). The website is being served on localhost:8080. All the HTML files are in the website folder, which you can go through to understand the structure of the website.

    You can open the web browser tab and navigate to localhost:8080/website/catalog.html to see one of the web pages.

    The App.java file has some boilerplate code to get you started. Within the main method, you will see a try block that creates a new Playwright instance:

    try (Playwright playwright = Playwright.create()) {
        ...
    }
    

    You can use this playwright instance for all future tasks. This is the entry point for all Playwright operations.

    You can create different browser instances using the playwright instance. You can create instances for different browsers like chromium, firefox, or webkit:

    Browser browser = playwright.webkit().launch();
    Browser browser = playwright.chromium().launch();
    Browser browser = playwright.firefox().launch();
    

    If you already have a Browser instance, you can check information about the browser using the name and browser.version, and other methods:

    String browserName = browser.browserType().name();
    String browserVersion = browser.version();
    String browserBinary = browser.browserType().executablePath();
    
  2. Challenge

    Locating Elements

    When writing end-to-end tests, you will need to find and locate particular elements on the web page. This could be to verify their content, interact with them, or check their attributes.

    The abstraction for web pages in Playwright is the Page class. And you can create a new page instance using the browser.newPage() method:

    Page page = browser.newPage();
    

    You can think of a Page as a representation of a web page in the browser. You can use this Page instance to interact with the page, navigate to different URLs, and locate elements on the page.

    Playwright allows you to locate elements and other attributes using an already-familiar CSS selector syntax. For example:

    // Navigates to a particular URL
    page.navigate("http://localhost:8080/website/catalog.html");
    // Get the title of the current page
    String title = page.title();
    // Get the current URL of the page
    String url = page.url();
    // Locate all elements with the class "some-class"
    List<Locator> elements = page.locator(".some-class").all()
    

    This code snippet will navigate to the catalog.html page and locate all elements with the class some-class, which will be stored in the elements list.

    The Locator class is a representation of an element on the page. You can use the Locator instance to interact with the element, get its attributes, or check its state.

    // Get the inner text of a Locator
    String innerText = page.locator(".some-class").first().innerText();
    // Get the value of the `href` attribute of a Locator
    String href = page.locator("a").first().getAttribute("href");
    

    The first() method of the Locator class returns the first element in the list of elements that match the selector. You can use this method to interact with the first element that matches the selector. On the other hand, the all() method returns a list of all elements that match the selector.

    Remember, the text within the page.locator method is a CSS selector. You can use any valid CSS selector to locate elements on the page.

  3. Challenge

    Interacting with Elements

    Once you have located an element, you can interact with it in various ways. In most cases, when you interact with an element, the state of the page will change. For example, clicking a button might open a modal, or typing into an input field might trigger a search.

    Playwright allows you to interact with elements in the same way a user would, so you can simulate user interactions in your tests:

    // click on the first link on the page
    page.locator("a").first().click();
    // fill in the input field with the label "Birth date"
    page.getByLabel("Birth date").fill("2020-02-02");
    // Check a checkbox
    page.locator("input[type='checkbox']").check();
    // Select an option from a dropdown, whose value is "option-value"
    page.locator("select").selectOption("option-value");
    

    Now, time to add some code to interact with different elements within the Globotickets website and inspect the new state of the page once you have complete the interaction.

  4. Challenge

    Making Assertions

    When writing tests, you will need to verify that the application behaves as expected. This could be checking the content of a page, the state of an element, or the URL of a page after an interaction.

    Playwright allows you to make assertions on the state of the page, elements, and the browser. For example:

    import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;
    
    // ...
    
    // check if the page title is "Home"
    assertThat(page.title()).isEqualTo("Home");
    // check if the element with the class "some-class" is visible
    assertThat(page.locator(".some-class").first()).isVisible();
    // check if an element has a particular CSS property
    assertThat(page.locator("p").first()).hasCSS("font-size", "16px");
    

    An assertion will throw an exception if the condition is not met. For this reason, assertions are mainly used in tests to verify that the application behaves as expected.

    To see this in action, you will need to add some assertions to the code. You'll make use of assertions to check the visibility of an element in the browser, and the appearance of an element through its CSS properties.

  5. Challenge

    Taking Screenshots

    When writing tests, you might want to take screenshots of the page at different points in the test.

    This can be useful for debugging, or to visually verify that the page looks as expected. This is especially useful when running end-to-end tests in a CI/CD pipeline, to ensure that a webpage looks as expected.

    Playwright allows you to take screenshots of the page, elements, or the browser window. For example:

    // take a screenshot of the page and save it to a file named "screenshot.png"
    page.screenshot(new Page.ScreenshotOptions().setPath("screenshot.png"));
    

Soham is a full stack developer with experience in building large scale web applications and services for clients across the globe.

What's a lab?

Hands-on Labs are real environments created by industry experts to help you learn. These environments help you gain knowledge and experience, practice without compromising your system, test without risk, destroy without fear, and let you learn from your mistakes. Hands-on Labs: practice your skills before delivering in the real world.

Provided environment for hands-on practice

We will provide the credentials and environment necessary for you to practice right within your browser.

Guided walkthrough

Follow along with the author’s guided walkthrough and build something new in your provided environment!

Did you know?

On average, you retain 75% more of your learning if you get time for practice.