Running Playwright and Selenium in LambdaTest cloud using Java.

Sameera De Silva
4 min readJan 9, 2024

--

This quick guide will equip you with the knowledge and code to run your Playwright automation scripts on LambdaTest’s robust cloud grid.
We’ll tackle everything from setting up your environment to customizing browser capabilities and connecting your tests to LambdaTest’s infrastructure.

There is no need of any LambdaTest dependencies

Here is code for Playwright and code is commented so you will get an idea.

import com.google.gson.JsonObject;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class PlayWrightBrowserSetUp {

// LambdaTest credentials (replace with your actual values)
public static final String LAMBDATEST_USERNAME = "username";
public static final String LAMBDATEST_ACCESS_KEY = "accesskey";



// Playwright instance
Playwright playwright;

// Browser instance
Browser browser;

// Method to set up the browser in LambdaTest
public void setBrowser() throws UnsupportedEncodingException {

// Indicate that the test is running on LambdaTest
System.out.println("Hello, running on LambdaTest !");

// Create a JsonObject to hold the browser capabilities
JsonObject capabilitiesObject = new JsonObject();

// Set the browser capabilities
capabilitiesObject.addProperty("browsername", "chrome");
capabilitiesObject.addProperty("browserVersion", "latest");// also can give as 120
capabilitiesObject.addProperty("platform", "Windows 10");
capabilitiesObject.addProperty("name", "Playwright in LambdaTest");
capabilitiesObject.addProperty("build", "APP Automation Build");
capabilitiesObject.addProperty("user", LAMBDATEST_USERNAME);
capabilitiesObject.addProperty("accessKey", LAMBDATEST_ACCESS_KEY);
capabilitiesObject.addProperty("headless", false);

// Create a Playwright instance
playwright = Playwright.create();

// Print driver paths (optional for debugging)
printDriverPaths(playwright);

// Get the Chromium browser type
BrowserType chromium = playwright.chromium();

// Encode the capabilities as a URL-encoded string
String caps = URLEncoder.encode(capabilitiesObject.toString(), "utf-8");

// Construct the CDP URL for connecting to LambdaTest
String cdpUrl = "wss://cdp.lambdatest.com/playwright?capabilities=" + caps;

// Connect to the browser on LambdaTest's grid
browser = chromium.connect(cdpUrl);
}

// Method to retrieve the browser instance
public Browser getBrowser() {
return browser;
}

// Optional method for debugging (prints driver paths)
private void printDriverPaths(Playwright playwright) {
//---
String driverPathOfChromium = playwright.chromium().executablePath();
System.out.println("Driver path of chromium: " + driverPathOfChromium);

/*
Playwright uses its own Firefox build.
That build is based on the Firefox Nightly build. That's why you are getting that browser. You won't be able to use the stock browser version.
So it will be Nightly Browser
*/
String driverPathOfFirefox = playwright.firefox().executablePath();
System.out.println("Driver path of Firefox: " + driverPathOfFirefox);
String driverPathOfWebKit = playwright.webkit().executablePath();
System.out.println("Driver path of WebKit: " + driverPathOfWebKit);
}
}

If you used TestNG you can mark the test status in LambdaTest UI using below code .

This is my test case

    @Test
public void firstTest() {
page.navigate("https://blazedemo.com/login");
Locator username = page.locator(TestPage.TXT_USERNAME);
username.fill("hello");
Locator password = page.locator(TestPage.TXT_PASSWORD);
password.fill("welcome123");

}
@AfterMethod
public void tearDown(ITestResult result) {
LambdaTestStatusMarker lambdaTestStatusMarker= new LambdaTestStatusMarker();
lambdaTestStatusMarker.markTestResultsInLambdaTest(page,result);
playWrightBrowserSetUp.closePlaywright(page,browser);
}

It calls the utility method that I created in another class.

import com.microsoft.playwright.Page;
import com.sam.testdata.GlobalConstantValues;
import org.testng.ITestResult;

public class LambdaTestStatusMarker {

String testNGResult;

// Use this method to update the test status in LambdaTest UI , then close the driver and update TestRail results using TestRailAgent results.
public void markTestResultsInLambdaTest(Page page, ITestResult result) {
// If it is a lambdaTest run, we need to update the UI , but this code is not working.
if(GlobalConstantValues.ISREMOTE==true){
int status = result.getStatus();

if (status == ITestResult.SUCCESS) {
System.out.println("Test Passed: " + result.getName());
testNGResult = "passed";

// page.evaluate("() => window.lambda-status = 'passed'"); // Now correct
} else if (status == ITestResult.FAILURE) {
System.out.println("Test Failed: " + result.getName());
testNGResult = "failed";

} else if (status == ITestResult.SKIP) {
System.out.println("Test Skipped: " + result.getName());
testNGResult = "skipped";

}

// Close the browser context, which also closes the page
// page.context().close();
System.out.println("All good status is--" + status);
setTestStatus("passed", "The test passed", page);

}


}
public static void setTestStatus(String status, String remark, Page page) {
Object result;
result = page.evaluate("_ => {}", "lambdatest_action: { \"action\": \"setTestStatus\", \"arguments\": { \"status\": \"" + status + "\", \"remark\": \"" + remark + "\"}}");

}
}

Refer- https://github.com/LambdaTest/playwright-sample/blob/main/playwright-java/src/test/java/com/lambdatest/PlaywrightTestSingle.java

Here is the code for Selenium

// LambdaTest credentials (replace with your actual values)
public static final String USERNAME = "username";
public static final String AUTOMATE_KEY = "automation key";

// LambdaTest grid URL
public static String gridURL = "@hub.lambdatest.com/wd/hub";

// Construct the full grid URL with credentials
public static final String URL = "https://" + USERNAME + ":" + AUTOMATE_KEY + gridURL;

// Use ThreadLocal to store a WebDriver instance for each thread
private static ThreadLocal<WebDriver> driver = new ThreadLocal<>();

// Method to set up the WebDriver for LambdaTest
public static void setDriver(String browser, String browserVersion, boolean isRemote) {

// Create DesiredCapabilities to specify browser and test settings
DesiredCapabilities capabilities = new DesiredCapabilities();

// Set desired browser capabilities
capabilities.setCapability("platform", "win10"); // Target operating system
capabilities.setCapability("resolution", "1024x768"); // Screen resolution
capabilities.setCapability("build", "MyTest Build"); // Build name for test results
capabilities.setCapability("name", "MyTest Selenium Automation"); // Test name
capabilities.setCapability("timezone", "New_York"); // Timezone for test execution
// ... (other capabilities for LambdaTest features)

// Set browser-specific capabilities
capabilities.setCapability("browserName", "chrome"); // Set the browser to Chrome
capabilities.setCapability("version", browserVersion); // Specify the browser version latest or 120
capabilities.setCapability("headless", false); // Run the browser in non-headless mode
// ... (other browser capabilities)

try {
// Create a RemoteWebDriver instance to connect to LambdaTest grid
driver.set(new RemoteWebDriver(new URL(URL), capabilities));
} catch (MalformedURLException e) {
System.out.println("Invalid grid URL");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}

If you used TestNG you can mark the test status in LambdaTest UI using below code which used Lambda hooks https://www.lambdatest.com/support/docs/lambda-hooks/

    @Test
private void justNavigate() {
driver.get("https://medium.com/");
WebElement username=driver.findElement(By.id("user_name"));
username.sendKeys("jdoe");

}

@AfterMethod
public void collectTestResult(ITestResult result) {

int status = result.getStatus();
// 1 means pass , 2 is failed and 3 is skipped.
if (status == ITestResult.SUCCESS) {
System.out.println("Test Passed: " + result.getName());
// Mark it as passed
((JavascriptExecutor) driver).executeScript("lambda-status=" + "passed");
} else if (status == ITestResult.FAILURE) {
System.out.println("Test Failed: " + result.getName());
// Mark it as failed
((JavascriptExecutor) driver).executeScript("lambda-status=" + "failed");
} else if (status == ITestResult.SKIP) {
System.out.println("Test Skipped: " + result.getName());
((JavascriptExecutor) driver).executeScript("lambda-status=" + "skipped");
}
// Make sure to close the driver only after ,test status were set above using driver,
driver.close();
TestRailAgent.collectResult(result);
}

Further reference-

https://www.lambdatest.com/capabilities-generator/?utm_source=github&utm_medium=repo&utm_campaign=Java-TestNG-Selenium
https://www.lambdatest.com/support/docs/selenium-automation-capabilities/#headless-browser
https://www.lambdatest.com/support/docs/testng-with-selenium-running-java-automation-scripts-on-lambdatest-selenium-grid/

--

--

No responses yet