Playwright Java — Hello World

Argo triwidodo
3 min readSep 21, 2023
Playwright Logo

Playwright is a modern automation framework developed by Microsoft that allows you to test web applications across multiple browsers and platforms. Unlike Selenium, which relies on WebDriver as an intermediary between the test script and the browser, Playwright communicates directly with the browser using native protocols. This makes Playwright faster compared to selenium.

Differentiate between Selenium & Playwright

In this blog post, I will show you how to set up Playwright for Java using Maven as the build tool. You will need to have Java and Maven installed on your machine before you proceed. You will also need to download the Playwright Java library and the browser binaries that you want to test with.

The first step is to create a Maven project and add the Playwright dependency to your pom.xml file. You can find the latest version of the Playwright dependency here. For example, if you want to use Playwright 1.38.0, you can add the following dependency:

        <dependency>
<groupId>com.microsoft.playwright</groupId>
<artifactId>playwright</artifactId>
<version>1.38.0</version>
</dependency>

The next step is to write a test script using Playwright. You can use any testing framework that you like, such as JUnit, TestNG or Spock. For this example, I will use JUnit 5. Here is a sample test script that launches a Chromium browser, navigates to a website and takes a screenshot:

import com.microsoft.playwright.Browser;
import com.microsoft.playwright.BrowserType;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.Playwright;
import org.junit.jupiter.api.Test;

import java.nio.file.Paths;


public class AppTest
{
@Test
public void playwrightTest(){
try (Playwright playwright = Playwright.create()) {
Browser browser;
browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));
Page page = browser.newPage();
page.navigate("https://playwright.dev/");
page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("example.png")));
}catch (Exception e){
e.printStackTrace();
}
}
}

The final step is to run the test script using Maven. You can use the following command:

mvn test

and it will launch new chromium browser and open the website.

Chromium Test

in the first time running the script, the script will be downloading their own browser build and will save it in your local cache, so in the next run it will not redownload the browsers.

Chromium Downloading and the other browsers.

You should see the test passing and an example.png file generated in your project directory.

That’s it! You have successfully set up Playwright for Java using Maven and written your first test script. You can now explore the Playwright API and write more tests for your web applications.

Next Time I will explain more about differentiate with selenium, what is pros, and what is cons compare to selenium.

Happy testing!

--

--