Run sample Playwright Java test

Step 1: Setup environment

Requirements

  • JDK (Highly recommended to use JDK 8 SE)
  • Java build framework
  • Access key
    • You can generate an Access key using the following instruction – Access key
  • Billing unit
    • The billing unit is your team’s unique identifier, or just the word “personal” in the case of an individual account.
      More information can be found here.

Step 2: Run sample test

After setup up the environment, you can run your first web test

package com.mobitru;


import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.microsoft.playwright.*;
import org.testng.annotations.Test;

import java.io.IOException;
import java.util.Base64;
import java.util.Map;
import java.util.UUID;

import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;

public class PlaywrightDemo {
    private static final String PROJECT_NAME = "<TEAM_CODE>";
    private static final String API_KEY = "mobitru_ak_...";
    private static final String BROWSER_HUB = "browserhub-us.mobitru.com";
    private static final String BROWSER_NAME = "chrome";
    private static final String PW_VERSION = "1.54.0";


    @Test
    public void demoTest() throws IOException {
        String credentials = PROJECT_NAME + ":" + API_KEY;

        // Encode the credentials as Base64
        String mobitruApiAccessToken = Base64.getEncoder().encodeToString(credentials.getBytes());
        String sessionName = UUID.randomUUID().toString();
        String wsEndpoint = String.format("wss://%s:%s@%s/playwright/%s/playwright-%s?headless=false&enableVideo=true&sessionName=%s",
                PROJECT_NAME, API_KEY, BROWSER_HUB, BROWSER_NAME, PW_VERSION, sessionName);
        try (Playwright playwright = Playwright.create()) {
            Browser browser = playwright.chromium().connect(wsEndpoint);
            Page page = browser.newPage();
            page.navigate("https://www.mobitru.com/");


            // Make a GET request
            APIRequestContext apiRequest = playwright.request().newContext(new APIRequest.NewContextOptions()
                    .setBaseURL("https://" + BROWSER_HUB)
                    .setExtraHTTPHeaders(Map.of(
                            "Authorization", "Basic " + mobitruApiAccessToken
                    )));
            APIResponse sessionInfo = apiRequest.get("/playwright/session/" + sessionName);
            String sessionId = new Gson().fromJson(sessionInfo.text(), JsonObject.class)
                    .get("sessionId")
                    .getAsString();

            assertThat(page.locator("button[class*='request-demo']")).isVisible();
            browser.close();
        }
    }

}

Scroll to Top