Run the sample Playwright C# test
Step 1: Setup environment
Requirements
- .NET 9.0
- Playwright 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.
- The billing unit is your team’s unique identifier, or just the word “personal” in the case of an individual account.
Step 2: Run sample test
After setup up the environment, you can run your first web test
using Microsoft.Playwright;
using NUnit.Framework;
using NUnit.Framework.Legacy;
using OpenQA.Selenium;
using OpenQA.Selenium.Appium;
using OpenQA.Selenium.Appium.iOS;
using OpenQA.Selenium.Support.UI;
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
namespace PlaywrightTests
{
public class PlaywrightDemoTest
{
private const string PROJECT_NAME = "<TEAM_CODE>";
private const string API_KEY = "mobitru_ak_...";
private const string BROWSER_HUB = "browserhub-us.mobitru.com";
private const string BROWSER_NAME = "chrome";
private const string PW_VERSION = "1.55.0";
[Test]
public void DemoTest()
{
string sessionName = Guid.NewGuid().ToString();
string wsEndpoint = $"wss://{PROJECT_NAME}:{API_KEY}@{BROWSER_HUB}/playwright/{BROWSER_NAME}/playwright-{PW_VERSION}?sessionName={sessionName}";
using var playwright = Microsoft.Playwright.Playwright.CreateAsync().GetAwaiter().GetResult();
var browser = playwright.Chromium.ConnectAsync(wsEndpoint).GetAwaiter().GetResult();
var page = browser.NewPageAsync().GetAwaiter().GetResult();
page.GotoAsync("https://www.mobitru.com/").GetAwaiter().GetResult();
string httpCredentials = $"{PROJECT_NAME}:{API_KEY}";
// Encode to Base64
string mobitruApiAccessToken = Convert.ToBase64String(Encoding.UTF8.GetBytes(httpCredentials));
var requestContext = playwright.APIRequest.NewContextAsync(new APIRequestNewContextOptions
{
BaseURL = $"https://{BROWSER_HUB}",
ExtraHTTPHeaders = new Dictionary<string, string>
{
{ "Authorization", $"Basic {mobitruApiAccessToken}" }
}
}).GetAwaiter().GetResult();
// Perform the GET request
var sessionInfo = requestContext.GetAsync($"/playwright/session/{sessionName}").GetAwaiter().GetResult();
var jsonResponse = sessionInfo.JsonAsync().GetAwaiter().GetResult();
var sessionId = jsonResponse?.GetProperty("sessionId");
var isButtonVisible = page.Locator("button[class*='request-demo']").IsVisibleAsync().GetAwaiter().GetResult();
Assert.That(isButtonVisible, Is.True, "The 'Request Demo' button should be visible, but it was not");
browser.CloseAsync().GetAwaiter().GetResult();
}
}
}