Skip to content

Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.

docs(dotnet): add test runner tabs to API testing and WebView2 guides (#42418)

Dmitry Gozman35fcef21d9b2
diff --git a/docs/src/api-testing-csharp.md b/docs/src/api-testing-csharp.md
index 6a8482e244..f608bc35e7 100644
--- a/docs/src/api-testing-csharp.md
+++ b/docs/src/api-testing-csharp.md
@@ -16,7 +16,7 @@ A few examples where it may come in handy:
All of that could be achieved via [APIRequestContext] methods.
-The following examples rely on the [`Microsoft.Playwright.MSTest`](./test-runners.md) package which creates a Playwright and Page instance for each test.
+The following examples rely on the MSTest, NUnit, xUnit or xUnit v3 [base classes](./test-runners.md) which create a Playwright and Page instance for each test.
## Writing API Test
@@ -31,7 +31,780 @@ The following example demonstrates how to use Playwright to test issues creation
GitHub API requires authorization, so we'll configure the token once for all tests. While at it, we'll also set the `baseURL` to simplify the tests.
+<Tabs
+ groupId="test-runners"
+ defaultValue="mstest"
+ values={[
+ {label: 'MSTest', value: 'mstest'},
+ {label: 'NUnit', value: 'nunit'},
+ {label: 'xUnit', value: 'xunit'},
+ {label: 'xUnit v3', value: 'xunit-v3'},
+ ]
+}>
+<TabItem value="mstest">
+
+```csharp
+using Microsoft.Playwright;
+using Microsoft.Playwright.MSTest;
+
+namespace PlaywrightTests;
+
+[TestClass]
+public class TestGitHubAPI : PlaywrightTest
+{
+ static string? API_TOKEN = Environment.GetEnvironmentVariable("GITHUB_API_TOKEN");
+
+ private IAPIRequestContext Request = null!;
+
+ [TestInitialize]
+ public async Task SetUpAPITesting()
+ {
+ await CreateAPIRequestContext();
+ }
+
+ private async Task CreateAPIRequestContext()
+ {
+ var headers = new Dictionary<string, string>();
+ // We set this header per GitHub guidelines.
+ headers.Add("Accept", "application/vnd.github.v3+json");
+ // Add authorization token to all requests.
+ // Assuming personal access token available in the environment.
+ headers.Add("Authorization", "token " + API_TOKEN);
+
+ Request = await this.Playwright.APIRequest.NewContextAsync(new() {
+ // All requests we send go to this API endpoint.
+ BaseURL = "https://api.github.com",
+ ExtraHTTPHeaders = headers,
+ });
+ }
+
+ [TestCleanup]
+ public async Task TearDownAPITesting()
+ {
+ await Request.DisposeAsync();
+ }
+}
+```
+
+</TabItem>
+<TabItem value="nunit">
+
+```csharp
+using Microsoft.Playwright;
+using Microsoft.Playwright.NUnit;
+using NUnit.Framework;
+
+namespace PlaywrightTests;
+
+[Parallelizable(ParallelScope.Self)]
+[TestFixture]
+public class TestGitHubAPI : PlaywrightTest
+{
+ static string? API_TOKEN = Environment.GetEnvironmentVariable("GITHUB_API_TOKEN");
+
+ private IAPIRequestContext Request = null!;
+
+ [SetUp]
+ public async Task SetUpAPITesting()
+ {
+ await CreateAPIRequestContext();
+ }
+
+ private async Task CreateAPIRequestContext()
+ {
+ var headers = new Dictionary<string, string>();
+ // We set this header per GitHub guidelines.
+ headers.Add("Accept", "application/vnd.github.v3+json");
+ // Add authorization token to all requests.
+ // Assuming personal access token available in the environment.
+ headers.Add("Authorization", "token " + API_TOKEN);
+
+ Request = await this.Playwright.APIRequest.NewContextAsync(new() {
+ // All requests we send go to this API endpoint.
+ BaseURL = "https://api.github.com",
+ ExtraHTTPHeaders = headers,
+ });
+ }
+
+ [TearDown]
+ public async Task TearDownAPITesting()
+ {
+ await Request.DisposeAsync();
+ }
+}
+```
+
+</TabItem>
+<TabItem value="xunit">
+
+```csharp
+using Microsoft.Playwright;
+using Microsoft.Playwright.Xunit;
+
+namespace PlaywrightTests;
+
+public class TestGitHubAPI : PlaywrightTest
+{
+ static string? API_TOKEN = Environment.GetEnvironmentVariable("GITHUB_API_TOKEN");
+
+ private IAPIRequestContext Request = null!;
+
+ public override async Task InitializeAsync()
+ {
+ await base.InitializeAsync();
+ await CreateAPIRequestContext();
+ }
+
+ private async Task CreateAPIRequestContext()
+ {
+ var headers = new Dictionary<string, string>();
+ // We set this header per GitHub guidelines.
+ headers.Add("Accept", "application/vnd.github.v3+json");
+ // Add authorization token to all requests.
+ // Assuming personal access token available in the environment.
+ headers.Add("Authorization", "token " + API_TOKEN);
+
+ Request = await this.Playwright.APIRequest.NewContextAsync(new() {
+ // All requests we send go to this API endpoint.
+ BaseURL = "https://api.github.com",
+ ExtraHTTPHeaders = headers,
+ });
+ }
+
+ public override async Task DisposeAsync()
+ {
+ await Request.DisposeAsync();
+ await base.DisposeAsync();
+ }
+}
+```
+
+</TabItem>
+<TabItem value="xunit-v3">
+
+```csharp
+using Microsoft.Playwright;
+using Microsoft.Playwright.Xunit.v3;
+
+namespace PlaywrightTests;
+
+public class TestGitHubAPI : PlaywrightTest
+{
+ static string? API_TOKEN = Environment.GetEnvironmentVariable("GITHUB_API_TOKEN");
+
+ private IAPIRequestContext Request = null!;
+
+ public override async Task InitializeAsync()
+ {
+ await base.InitializeAsync();
+ await CreateAPIRequestContext();
+ }
+
+ private async Task CreateAPIRequestContext()
+ {
+ var headers = new Dictionary<string, string>();
+ // We set this header per GitHub guidelines.
+ headers.Add("Accept", "application/vnd.github.v3+json");
+ // Add authorization token to all requests.
+ // Assuming personal access token available in the environment.
+ headers.Add("Authorization", "token " + API_TOKEN);
+
+ Request = await this.Playwright.APIRequest.NewContextAsync(new() {
+ // All requests we send go to this API endpoint.
+ BaseURL = "https://api.github.com",
+ ExtraHTTPHeaders = headers,
+ });
+ }
+
+ public override async Task DisposeAsync()
+ {
+ await Request.DisposeAsync();
+ await base.DisposeAsync();
+ }
+}
+```
+
+</TabItem>
+</Tabs>
+
+### Write tests
+
+Now that we initialized request object we can add a few tests that will create new issues in the repository.
+
+<Tabs
+ groupId="test-runners"
+ defaultValue="mstest"
+ values={[
+ {label: 'MSTest', value: 'mstest'},
+ {label: 'NUnit', value: 'nunit'},
+ {label: 'xUnit', value: 'xunit'},
+ {label: 'xUnit v3', value: 'xunit-v3'},
+ ]
+}>
+<TabItem value="mstest">
+
+```csharp
+using System.Text.Json;
+using Microsoft.Playwright;
+using Microsoft.Playwright.MSTest;
+
+namespace PlaywrightTests;
+
+[TestClass]
+public class TestGitHubAPI : PlaywrightTest
+{
+ static string REPO = "test";
+ static string USER = Environment.GetEnvironmentVariable("GITHUB_USER");
+ static string? API_TOKEN = Environment.GetEnvironmentVariable("GITHUB_API_TOKEN");
+
+ private IAPIRequestContext Request = null!;
+
+ [TestMethod]
+ public async Task ShouldCreateBugReport()
+ {
+ var data = new Dictionary<string, string>
+ {
+ { "title", "[Bug] report 1" },
+ { "body", "Bug description" }
+ };
+ var newIssue = await Request.PostAsync("/repos/" + USER + "/" + REPO + "/issues", new() { DataObject = data });
+ await Expect(newIssue).ToBeOKAsync();
+
+ var issues = await Request.GetAsync("/repos/" + USER + "/" + REPO + "/issues");
+ await Expect(newIssue).ToBeOKAsync();
+ var issuesJsonResponse = await issues.JsonAsync();
+ JsonElement? issue = null;
+ foreach (JsonElement issueObj in issuesJsonResponse?.EnumerateArray())
+ {
+ if (issueObj.TryGetProperty("title", out var title) == true)
+ {
+ if (title.GetString() == "[Bug] report 1")
+ {
+ issue = issueObj;
+ }
+ }
+ }
+ Assert.IsNotNull(issue);
+ Assert.AreEqual("Bug description", issue?.GetProperty("body").GetString());
+ }
+
+ [TestMethod]
+ public async Task ShouldCreateFeatureRequests()
+ {
+ var data = new Dictionary<string, string>
+ {
+ { "title", "[Feature] request 1" },
+ { "body", "Feature description" }
+ };
+ var newIssue = await Request.PostAsync("/repos/" + USER + "/" + REPO + "/issues", new() { DataObject = data });
+ await Expect(newIssue).ToBeOKAsync();
+
+ var issues = await Request.GetAsync("/repos/" + USER + "/" + REPO + "/issues");
+ await Expect(newIssue).ToBeOKAsync();
+ var issuesJsonResponse = await issues.JsonAsync();
+
+ JsonElement? issue = null;
+ foreach (JsonElement issueObj in issuesJsonResponse?.EnumerateArray())
+ {
+ if (issueObj.TryGetProperty("title", out var title) == true)
+ {
+ if (title.GetString() == "[Feature] request 1")
+ {
+ issue = issueObj;
+ }
+ }
+ }
+ Assert.IsNotNull(issue);
+ Assert.AreEqual("Feature description", issue?.GetProperty("body").GetString());
+ }
+
+ // ...
+}
+```
+
+</TabItem>
+<TabItem value="nunit">
+
+```csharp
+using System.Text.Json;
+using Microsoft.Playwright;
+using Microsoft.Playwright.NUnit;
+using NUnit.Framework;
+
+namespace PlaywrightTests;
+
+[Parallelizable(ParallelScope.Self)]
+[TestFixture]
+public class TestGitHubAPI : PlaywrightTest
+{
+ static string REPO = "test";
+ static string USER = Environment.GetEnvironmentVariable("GITHUB_USER");
+ static string? API_TOKEN = Environment.GetEnvironmentVariable("GITHUB_API_TOKEN");
+
+ private IAPIRequestContext Request = null!;
+
+ [Test]
+ public async Task ShouldCreateBugReport()
+ {
+ var data = new Dictionary<string, string>
+ {
+ { "title", "[Bug] report 1" },
+ { "body", "Bug description" }
+ };
+ var newIssue = await Request.PostAsync("/repos/" + USER + "/" + REPO + "/issues", new() { DataObject = data });
+ await Expect(newIssue).ToBeOKAsync();
+
+ var issues = await Request.GetAsync("/repos/" + USER + "/" + REPO + "/issues");
+ await Expect(newIssue).ToBeOKAsync();
+ var issuesJsonResponse = await issues.JsonAsync();
+ JsonElement? issue = null;
+ foreach (JsonElement issueObj in issuesJsonResponse?.EnumerateArray())
+ {
+ if (issueObj.TryGetProperty("title", out var title) == true)
+ {
+ if (title.GetString() == "[Bug] report 1")
+ {
+ issue = issueObj;
+ }
+ }
+ }
+ Assert.That(issue, Is.Not.Null);
+ Assert.That(issue?.GetProperty("body").GetString(), Is.EqualTo("Bug description"));
+ }
+
+ [Test]
+ public async Task ShouldCreateFeatureRequests()
+ {
+ var data = new Dictionary<string, string>
+ {
+ { "title", "[Feature] request 1" },
+ { "body", "Feature description" }
+ };
+ var newIssue = await Request.PostAsync("/repos/" + USER + "/" + REPO + "/issues", new() { DataObject = data });
+ await Expect(newIssue).ToBeOKAsync();
+
+ var issues = await Request.GetAsync("/repos/" + USER + "/" + REPO + "/issues");
+ await Expect(newIssue).ToBeOKAsync();
+ var issuesJsonResponse = await issues.JsonAsync();
+
+ JsonElement? issue = null;
+ foreach (JsonElement issueObj in issuesJsonResponse?.EnumerateArray())
+ {
+ if (issueObj.TryGetProperty("title", out var title) == true)
+ {
+ if (title.GetString() == "[Feature] request 1")
+ {
+ issue = issueObj;
+ }
+ }
+ }
+ Assert.That(issue, Is.Not.Null);
+ Assert.That(issue?.GetProperty("body").GetString(), Is.EqualTo("Feature description"));
+ }
+
+ // ...
+}
+```
+
+</TabItem>
+<TabItem value="xunit">
+
+```csharp
+using System.Text.Json;
+using Microsoft.Playwright;
+using Microsoft.Playwright.Xunit;
+
+namespace PlaywrightTests;
+
+public class TestGitHubAPI : PlaywrightTest
+{
+ static string REPO = "test";
+ static string USER = Environment.GetEnvironmentVariable("GITHUB_USER");
+ static string? API_TOKEN = Environment.GetEnvironmentVariable("GITHUB_API_TOKEN");
+
+ private IAPIRequestContext Request = null!;
+
+ [Fact]
+ public async Task ShouldCreateBugReport()
+ {
+ var data = new Dictionary<string, string>
+ {
+ { "title", "[Bug] report 1" },
+ { "body", "Bug description" }
+ };
+ var newIssue = await Request.PostAsync("/repos/" + USER + "/" + REPO + "/issues", new() { DataObject = data });
+ await Expect(newIssue).ToBeOKAsync();
+
+ var issues = await Request.GetAsync("/repos/" + USER + "/" + REPO + "/issues");
+ await Expect(newIssue).ToBeOKAsync();
+ var issuesJsonResponse = await issues.JsonAsync();
+ JsonElement? issue = null;
+ foreach (JsonElement issueObj in issuesJsonResponse?.EnumerateArray())
+ {
+ if (issueObj.TryGetProperty("title", out var title) == true)
+ {
+ if (title.GetString() == "[Bug] report 1")
+ {
+ issue = issueObj;
+ }
+ }
+ }
+ Assert.NotNull(issue);
+ Assert.Equal("Bug description", issue?.GetProperty("body").GetString());
+ }
+
+ [Fact]
+ public async Task ShouldCreateFeatureRequests()
+ {
+ var data = new Dictionary<string, string>
+ {
+ { "title", "[Feature] request 1" },
+ { "body", "Feature description" }
+ };
+ var newIssue = await Request.PostAsync("/repos/" + USER + "/" + REPO + "/issues", new() { DataObject = data });
+ await Expect(newIssue).ToBeOKAsync();
+
+ var issues = await Request.GetAsync("/repos/" + USER + "/" + REPO + "/issues");
+ await Expect(newIssue).ToBeOKAsync();
+ var issuesJsonResponse = await issues.JsonAsync();
+
+ JsonElement? issue = null;
+ foreach (JsonElement issueObj in issuesJsonResponse?.EnumerateArray())
+ {
+ if (issueObj.TryGetProperty("title", out var title) == true)
+ {
+ if (title.GetString() == "[Feature] request 1")
+ {
+ issue = issueObj;
+ }
+ }
+ }
+ Assert.NotNull(issue);
+ Assert.Equal("Feature description", issue?.GetProperty("body").GetString());
+ }
+
+ // ...
+}
+```
+
+</TabItem>
+<TabItem value="xunit-v3">
+
+```csharp
+using System.Text.Json;
+using Microsoft.Playwright;
+using Microsoft.Playwright.Xunit.v3;
+
+namespace PlaywrightTests;
+
+public class TestGitHubAPI : PlaywrightTest
+{
+ static string REPO = "test";
+ static string USER = Environment.GetEnvironmentVariable("GITHUB_USER");
+ static string? API_TOKEN = Environment.GetEnvironmentVariable("GITHUB_API_TOKEN");
+
+ private IAPIRequestContext Request = null!;
+
+ [Fact]
+ public async Task ShouldCreateBugReport()
+ {
+ var data = new Dictionary<string, string>
+ {
+ { "title", "[Bug] report 1" },
+ { "body", "Bug description" }
+ };
+ var newIssue = await Request.PostAsync("/repos/" + USER + "/" + REPO + "/issues", new() { DataObject = data });
+ await Expect(newIssue).ToBeOKAsync();
+
+ var issues = await Request.GetAsync("/repos/" + USER + "/" + REPO + "/issues");
+ await Expect(newIssue).ToBeOKAsync();
+ var issuesJsonResponse = await issues.JsonAsync();
+ JsonElement? issue = null;
+ foreach (JsonElement issueObj in issuesJsonResponse?.EnumerateArray())
+ {
+ if (issueObj.TryGetProperty("title", out var title) == true)
+ {
+ if (title.GetString() == "[Bug] report 1")
+ {
+ issue = issueObj;
+ }
+ }
+ }
+ Assert.NotNull(issue);
+ Assert.Equal("Bug description", issue?.GetProperty("body").GetString());
+ }
+
+ [Fact]
+ public async Task ShouldCreateFeatureRequests()
+ {
+ var data = new Dictionary<string, string>
+ {
+ { "title", "[Feature] request 1" },
+ { "body", "Feature description" }
+ };
+ var newIssue = await Request.PostAsync("/repos/" + USER + "/" + REPO + "/issues", new() { DataObject = data });
+ await Expect(newIssue).ToBeOKAsync();
+
+ var issues = await Request.GetAsync("/repos/" + USER + "/" + REPO + "/issues");
+ await Expect(newIssue).ToBeOKAsync();
+ var issuesJsonResponse = await issues.JsonAsync();
+
+ JsonElement? issue = null;
+ foreach (JsonElement issueObj in issuesJsonResponse?.EnumerateArray())
+ {
+ if (issueObj.TryGetProperty("title", out var title) == true)
+ {
+ if (title.GetString() == "[Feature] request 1")
+ {
+ issue = issueObj;
+ }
+ }
+ }
+ Assert.NotNull(issue);
+ Assert.Equal("Feature description", issue?.GetProperty("body").GetString());
+ }
+
+ // ...
+}
+```
+
+</TabItem>
+</Tabs>
+
+### Setup and teardown
+
+These tests assume that repository exists. You probably want to create a new one before running tests and delete it afterwards.
+
+<Tabs
+ groupId="test-runners"
+ defaultValue="mstest"
+ values={[
+ {label: 'MSTest', value: 'mstest'},
+ {label: 'NUnit', value: 'nunit'},
+ {label: 'xUnit', value: 'xunit'},
+ {label: 'xUnit v3', value: 'xunit-v3'},
+ ]
+}>
+<TabItem value="mstest">
+
+Use `[TestInitialize]` and `[TestCleanup]` hooks for that.
+
+```csharp
+using System.Text.Json;
+using Microsoft.Playwright;
+using Microsoft.Playwright.MSTest;
+
+namespace PlaywrightTests;
+
+[TestClass]
+public class TestGitHubAPI : PlaywrightTest
+{
+ // ...
+ [TestInitialize]
+ public async Task SetUpAPITesting()
+ {
+ await CreateAPIRequestContext();
+ await CreateTestRepository();
+ }
+
+ private async Task CreateTestRepository()
+ {
+ var resp = await Request.PostAsync("/user/repos", new()
+ {
+ DataObject = new Dictionary<string, string>()
+ {
+ ["name"] = REPO,
+ },
+ });
+ await Expect(resp).ToBeOKAsync();
+ }
+
+ [TestCleanup]
+ public async Task TearDownAPITesting()
+ {
+ await DeleteTestRepository();
+ await Request.DisposeAsync();
+ }
+
+ private async Task DeleteTestRepository()
+ {
+ var resp = await Request.DeleteAsync("/repos/" + USER + "/" + REPO);
+ await Expect(resp).ToBeOKAsync();
+ }
+}
+```
+
+</TabItem>
+<TabItem value="nunit">
+
+Use `[SetUp]` and `[TearDown]` hooks for that.
+
+```csharp
+using System.Text.Json;
+using Microsoft.Playwright;
+using Microsoft.Playwright.NUnit;
+using NUnit.Framework;
+
+namespace PlaywrightTests;
+
+[Parallelizable(ParallelScope.Self)]
+[TestFixture]
+public class TestGitHubAPI : PlaywrightTest
+{
+ // ...
+ [SetUp]
+ public async Task SetUpAPITesting()
+ {
+ await CreateAPIRequestContext();
+ await CreateTestRepository();
+ }
+
+ private async Task CreateTestRepository()
+ {
+ var resp = await Request.PostAsync("/user/repos", new()
+ {
+ DataObject = new Dictionary<string, string>()
+ {
+ ["name"] = REPO,
+ },
+ });
+ await Expect(resp).ToBeOKAsync();
+ }
+
+ [TearDown]
+ public async Task TearDownAPITesting()
+ {
+ await DeleteTestRepository();
+ await Request.DisposeAsync();
+ }
+
+ private async Task DeleteTestRepository()
+ {
+ var resp = await Request.DeleteAsync("/repos/" + USER + "/" + REPO);
+ await Expect(resp).ToBeOKAsync();
+ }
+}
+```
+
+</TabItem>
+<TabItem value="xunit">
+
+Override the `InitializeAsync` and `DisposeAsync` methods for that.
+
+```csharp
+using System.Text.Json;
+using Microsoft.Playwright;
+using Microsoft.Playwright.Xunit;
+
+namespace PlaywrightTests;
+
+public class TestGitHubAPI : PlaywrightTest
+{
+ // ...
+ public override async Task InitializeAsync()
+ {
+ await base.InitializeAsync();
+ await CreateAPIRequestContext();
+ await CreateTestRepository();
+ }
+
+ private async Task CreateTestRepository()
+ {
+ var resp = await Request.PostAsync("/user/repos", new()
+ {
+ DataObject = new Dictionary<string, string>()
+ {
+ ["name"] = REPO,
+ },
+ });
+ await Expect(resp).ToBeOKAsync();
+ }
+
+ public override async Task DisposeAsync()
+ {
+ await DeleteTestRepository();
+ await Request.DisposeAsync();
+ await base.DisposeAsync();
+ }
+
+ private async Task DeleteTestRepository()
+ {
+ var resp = await Request.DeleteAsync("/repos/" + USER + "/" + REPO);
+ await Expect(resp).ToBeOKAsync();
+ }
+}
+```
+
+</TabItem>
+<TabItem value="xunit-v3">
+
+Override the `InitializeAsync` and `DisposeAsync` methods for that.
+
+```csharp
+using System.Text.Json;
+using Microsoft.Playwright;
+using Microsoft.Playwright.Xunit.v3;
+
+namespace PlaywrightTests;
+
+public class TestGitHubAPI : PlaywrightTest
+{
+ // ...
+ public override async Task InitializeAsync()
+ {
+ await base.InitializeAsync();
+ await CreateAPIRequestContext();
+ await CreateTestRepository();
+ }
+
+ private async Task CreateTestRepository()
+ {
+ var resp = await Request.PostAsync("/user/repos", new()
+ {
+ DataObject = new Dictionary<string, string>()
+ {
+ ["name"] = REPO,
+ },
+ });
+ await Expect(resp).ToBeOKAsync();
+ }
+
+ public override async Task DisposeAsync()
+ {
+ await DeleteTestRepository();
+ await Request.DisposeAsync();
+ await base.DisposeAsync();
+ }
+
+ private async Task DeleteTestRepository()
+ {
+ var resp = await Request.DeleteAsync("/repos/" + USER + "/" + REPO);
+ await Expect(resp).ToBeOKAsync();
+ }
+}
+```
+
+</TabItem>
+</Tabs>
+
+### Complete test example
+
+Here is the complete example of an API test:
+
+<Tabs
+ groupId="test-runners"
+ defaultValue="mstest"
+ values={[
+ {label: 'MSTest', value: 'mstest'},
+ {label: 'NUnit', value: 'nunit'},
+ {label: 'xUnit', value: 'xunit'},
+ {label: 'xUnit v3', value: 'xunit-v3'},
+ ]
+}>
+<TabItem value="mstest">
+
```csharp
+using System.Text.Json;
using Microsoft.Playwright;
using Microsoft.Playwright.MSTest;
@@ -40,60 +813,276 @@ namespace PlaywrightTests;
[TestClass]
public class TestGitHubAPI : PlaywrightTest
{
+ static string REPO = "test-repo-2";
+ static string USER = Environment.GetEnvironmentVariable("GITHUB_USER");
+ static string? API_TOKEN = Environment.GetEnvironmentVariable("GITHUB_API_TOKEN");
+
+ private IAPIRequestContext Request = null!;
+
+ [TestMethod]
+ public async Task ShouldCreateBugReport()
+ {
+ var data = new Dictionary<string, string>
+ {
+ { "title", "[Bug] report 1" },
+ { "body", "Bug description" }
+ };
+ var newIssue = await Request.PostAsync("/repos/" + USER + "/" + REPO + "/issues", new() { DataObject = data });
+ await Expect(newIssue).ToBeOKAsync();
+
+ var issues = await Request.GetAsync("/repos/" + USER + "/" + REPO + "/issues");
+ await Expect(newIssue).ToBeOKAsync();
+ var issuesJsonResponse = await issues.JsonAsync();
+ JsonElement? issue = null;
+ foreach (JsonElement issueObj in issuesJsonResponse?.EnumerateArray())
+ {
+ if (issueObj.TryGetProperty("title", out var title) == true)
+ {
+ if (title.GetString() == "[Bug] report 1")
+ {
+ issue = issueObj;
+ }
+ }
+ }
+ Assert.IsNotNull(issue);
+ Assert.AreEqual("Bug description", issue?.GetProperty("body").GetString());
+ }
+
+ [TestMethod]
+ public async Task ShouldCreateFeatureRequests()
+ {
+ var data = new Dictionary<string, string>
+ {
+ { "title", "[Feature] request 1" },
+ { "body", "Feature description" }
+ };
+ var newIssue = await Request.PostAsync("/repos/" + USER + "/" + REPO + "/issues", new() { DataObject = data });
+ await Expect(newIssue).ToBeOKAsync();
+
+ var issues = await Request.GetAsync("/repos/" + USER + "/" + REPO + "/issues");
+ await Expect(newIssue).ToBeOKAsync();
+ var issuesJsonResponse = await issues.JsonAsync();
+
+ JsonElement? issue = null;
+ foreach (JsonElement issueObj in issuesJsonResponse?.EnumerateArray())
+ {
+ if (issueObj.TryGetProperty("title", out var title) == true)
+ {
+ if (title.GetString() == "[Feature] request 1")
+ {
+ issue = issueObj;
+ }
+ }
+ }
+ Assert.IsNotNull(issue);
+ Assert.AreEqual("Feature description", issue?.GetProperty("body").GetString());
+ }
+
+ [TestInitialize]
+ public async Task SetUpAPITesting()
+ {
+ await CreateAPIRequestContext();
+ await CreateTestRepository();
+ }
+
+ private async Task CreateAPIRequestContext()
+ {
+ var headers = new Dictionary<string, string>
+ {
+ // We set this header per GitHub guidelines.
+ { "Accept", "application/vnd.github.v3+json" },
+ // Add authorization token to all requests.
+ // Assuming personal access token available in the environment.
+ { "Authorization", "token " + API_TOKEN }
+ };
+
+ Request = await Playwright.APIRequest.NewContextAsync(new()
+ {
+ // All requests we send go to this API endpoint.
+ BaseURL = "https://api.github.com",
+ ExtraHTTPHeaders = headers,
+ });
+ }
+
+ private async Task CreateTestRepository()
+ {
+ var resp = await Request.PostAsync("/user/repos", new()
+ {
+ DataObject = new Dictionary<string, string>()
+ {
+ ["name"] = REPO,
+ },
+ });
+ await Expect(resp).ToBeOKAsync();
+ }
+
+ [TestCleanup]
+ public async Task TearDownAPITesting()
+ {
+ await DeleteTestRepository();
+ await Request.DisposeAsync();
+ }
+
+ private async Task DeleteTestRepository()
+ {
+ var resp = await Request.DeleteAsync("/repos/" + USER + "/" + REPO);
+ await Expect(resp).ToBeOKAsync();
+ }
+}
+```
+
+</TabItem>
+<TabItem value="nunit">
+
+```csharp
+using System.Text.Json;
+using Microsoft.Playwright;
+using Microsoft.Playwright.NUnit;
+using NUnit.Framework;
+
+namespace PlaywrightTests;
+
+[Parallelizable(ParallelScope.Self)]
+[TestFixture]
+public class TestGitHubAPI : PlaywrightTest
+{
+ static string REPO = "test-repo-2";
+ static string USER = Environment.GetEnvironmentVariable("GITHUB_USER");
static string? API_TOKEN = Environment.GetEnvironmentVariable("GITHUB_API_TOKEN");
- private IAPIRequestContext Request = null!;
+ private IAPIRequestContext Request = null!;
+
+ [Test]
+ public async Task ShouldCreateBugReport()
+ {
+ var data = new Dictionary<string, string>
+ {
+ { "title", "[Bug] report 1" },
+ { "body", "Bug description" }
+ };
+ var newIssue = await Request.PostAsync("/repos/" + USER + "/" + REPO + "/issues", new() { DataObject = data });
+ await Expect(newIssue).ToBeOKAsync();
+
+ var issues = await Request.GetAsync("/repos/" + USER + "/" + REPO + "/issues");
+ await Expect(newIssue).ToBeOKAsync();
+ var issuesJsonResponse = await issues.JsonAsync();
+ JsonElement? issue = null;
+ foreach (JsonElement issueObj in issuesJsonResponse?.EnumerateArray())
+ {
+ if (issueObj.TryGetProperty("title", out var title) == true)
+ {
+ if (title.GetString() == "[Bug] report 1")
+ {
+ issue = issueObj;
+ }
+ }
+ }
+ Assert.That(issue, Is.Not.Null);
+ Assert.That(issue?.GetProperty("body").GetString(), Is.EqualTo("Bug description"));
+ }
+
+ [Test]
+ public async Task ShouldCreateFeatureRequests()
+ {
+ var data = new Dictionary<string, string>
+ {
+ { "title", "[Feature] request 1" },
+ { "body", "Feature description" }
+ };
+ var newIssue = await Request.PostAsync("/repos/" + USER + "/" + REPO + "/issues", new() { DataObject = data });
+ await Expect(newIssue).ToBeOKAsync();
+
+ var issues = await Request.GetAsync("/repos/" + USER + "/" + REPO + "/issues");
+ await Expect(newIssue).ToBeOKAsync();
+ var issuesJsonResponse = await issues.JsonAsync();
- [TestInitialize]
+ JsonElement? issue = null;
+ foreach (JsonElement issueObj in issuesJsonResponse?.EnumerateArray())
+ {
+ if (issueObj.TryGetProperty("title", out var title) == true)
+ {
+ if (title.GetString() == "[Feature] request 1")
+ {
+ issue = issueObj;
+ }
+ }
+ }
+ Assert.That(issue, Is.Not.Null);
+ Assert.That(issue?.GetProperty("body").GetString(), Is.EqualTo("Feature description"));
+ }
+
+ [SetUp]
public async Task SetUpAPITesting()
{
await CreateAPIRequestContext();
+ await CreateTestRepository();
}
private async Task CreateAPIRequestContext()
{
- var headers = new Dictionary<string, string>();
- // We set this header per GitHub guidelines.
- headers.Add("Accept", "application/vnd.github.v3+json");
- // Add authorization token to all requests.
- // Assuming personal access token available in the environment.
- headers.Add("Authorization", "token " + API_TOKEN);
+ var headers = new Dictionary<string, string>
+ {
+ // We set this header per GitHub guidelines.
+ { "Accept", "application/vnd.github.v3+json" },
+ // Add authorization token to all requests.
+ // Assuming personal access token available in the environment.
+ { "Authorization", "token " + API_TOKEN }
+ };
- Request = await this.Playwright.APIRequest.NewContextAsync(new() {
+ Request = await Playwright.APIRequest.NewContextAsync(new()
+ {
// All requests we send go to this API endpoint.
BaseURL = "https://api.github.com",
ExtraHTTPHeaders = headers,
});
}
- [TestCleanup]
+ private async Task CreateTestRepository()
+ {
+ var resp = await Request.PostAsync("/user/repos", new()
+ {
+ DataObject = new Dictionary<string, string>()
+ {
+ ["name"] = REPO,
+ },
+ });
+ await Expect(resp).ToBeOKAsync();
+ }
+
+ [TearDown]
public async Task TearDownAPITesting()
{
+ await DeleteTestRepository();
await Request.DisposeAsync();
}
+
+ private async Task DeleteTestRepository()
+ {
+ var resp = await Request.DeleteAsync("/repos/" + USER + "/" + REPO);
+ await Expect(resp).ToBeOKAsync();
+ }
}
```
-### Write tests
+</TabItem>
+<TabItem value="xunit">
-Now that we initialized request object we can add a few tests that will create new issues in the repository.
```csharp
using System.Text.Json;
using Microsoft.Playwright;
-using Microsoft.Playwright.MSTest;
+using Microsoft.Playwright.Xunit;
namespace PlaywrightTests;
-[TestClass]
public class TestGitHubAPI : PlaywrightTest
{
- static string REPO = "test";
+ static string REPO = "test-repo-2";
static string USER = Environment.GetEnvironmentVariable("GITHUB_USER");
static string? API_TOKEN = Environment.GetEnvironmentVariable("GITHUB_API_TOKEN");
private IAPIRequestContext Request = null!;
- [TestMethod]
+ [Fact]
public async Task ShouldCreateBugReport()
{
var data = new Dictionary<string, string>
@@ -118,11 +1107,11 @@ public class TestGitHubAPI : PlaywrightTest
}
}
}
- Assert.IsNotNull(issue);
- Assert.AreEqual("Bug description", issue?.GetProperty("body").GetString());
+ Assert.NotNull(issue);
+ Assert.Equal("Bug description", issue?.GetProperty("body").GetString());
}
- [TestMethod]
+ [Fact]
public async Task ShouldCreateFeatureRequests()
{
var data = new Dictionary<string, string>
@@ -148,36 +1137,36 @@ public class TestGitHubAPI : PlaywrightTest
}
}
}
- Assert.IsNotNull(issue);
- Assert.AreEqual("Feature description", issue?.GetProperty("body").GetString());
+ Assert.NotNull(issue);
+ Assert.Equal("Feature description", issue?.GetProperty("body").GetString());
}
- // ...
-}
-```
-
-### Setup and teardown
-
-These tests assume that repository exists. You probably want to create a new one before running tests and delete it afterwards. Use `[SetUp]` and `[TearDown]` hooks for that.
-
-```csharp
-using System.Text.Json;
-using Microsoft.Playwright;
-using Microsoft.Playwright.MSTest;
-
-namespace PlaywrightTests;
-
-[TestClass]
-public class TestGitHubAPI : PlaywrightTest
-{
- // ...
- [TestInitialize]
- public async Task SetUpAPITesting()
+ public override async Task InitializeAsync()
{
+ await base.InitializeAsync();
await CreateAPIRequestContext();
await CreateTestRepository();
}
+ private async Task CreateAPIRequestContext()
+ {
+ var headers = new Dictionary<string, string>
+ {
+ // We set this header per GitHub guidelines.
+ { "Accept", "application/vnd.github.v3+json" },
+ // Add authorization token to all requests.
+ // Assuming personal access token available in the environment.
+ { "Authorization", "token " + API_TOKEN }
+ };
+
+ Request = await Playwright.APIRequest.NewContextAsync(new()
+ {
+ // All requests we send go to this API endpoint.
+ BaseURL = "https://api.github.com",
+ ExtraHTTPHeaders = headers,
+ });
+ }
+
private async Task CreateTestRepository()
{
var resp = await Request.PostAsync("/user/repos", new()
@@ -190,11 +1179,11 @@ public class TestGitHubAPI : PlaywrightTest
await Expect(resp).ToBeOKAsync();
}
- [TestCleanup]
- public async Task TearDownAPITesting()
+ public override async Task DisposeAsync()
{
await DeleteTestRepository();
await Request.DisposeAsync();
+ await base.DisposeAsync();
}
private async Task DeleteTestRepository()
@@ -205,18 +1194,16 @@ public class TestGitHubAPI : PlaywrightTest
}
```
-### Complete test example
-
-Here is the complete example of an API test:
+</TabItem>
+<TabItem value="xunit-v3">
```csharp
using System.Text.Json;
using Microsoft.Playwright;
-using Microsoft.Playwright.MSTest;
+using Microsoft.Playwright.Xunit.v3;
namespace PlaywrightTests;
-[TestClass]
public class TestGitHubAPI : PlaywrightTest
{
static string REPO = "test-repo-2";
@@ -225,7 +1212,7 @@ public class TestGitHubAPI : PlaywrightTest
private IAPIRequestContext Request = null!;
- [TestMethod]
+ [Fact]
public async Task ShouldCreateBugReport()
{
var data = new Dictionary<string, string>
@@ -250,11 +1237,11 @@ public class TestGitHubAPI : PlaywrightTest
}
}
}
- Assert.IsNotNull(issue);
- Assert.AreEqual("Bug description", issue?.GetProperty("body").GetString());
+ Assert.NotNull(issue);
+ Assert.Equal("Bug description", issue?.GetProperty("body").GetString());
}
- [TestMethod]
+ [Fact]
public async Task ShouldCreateFeatureRequests()
{
var data = new Dictionary<string, string>
@@ -280,13 +1267,13 @@ public class TestGitHubAPI : PlaywrightTest
}
}
}
- Assert.IsNotNull(issue);
- Assert.AreEqual("Feature description", issue?.GetProperty("body").GetString());
+ Assert.NotNull(issue);
+ Assert.Equal("Feature description", issue?.GetProperty("body").GetString());
}
- [TestInitialize]
- public async Task SetUpAPITesting()
+ public override async Task InitializeAsync()
{
+ await base.InitializeAsync();
await CreateAPIRequestContext();
await CreateTestRepository();
}
@@ -322,11 +1309,11 @@ public class TestGitHubAPI : PlaywrightTest
await Expect(resp).ToBeOKAsync();
}
- [TestCleanup]
- public async Task TearDownAPITesting()
+ public override async Task DisposeAsync()
{
await DeleteTestRepository();
await Request.DisposeAsync();
+ await base.DisposeAsync();
}
private async Task DeleteTestRepository()
@@ -337,13 +1324,29 @@ public class TestGitHubAPI : PlaywrightTest
}
```
+</TabItem>
+</Tabs>
+
## Prepare server state via API calls
The following test creates a new issue via API and then navigates to the list of all issues in the
project to check that it appears at the top of the list. The check is performed using [LocatorAssertions].
+<Tabs
+ groupId="test-runners"
+ defaultValue="mstest"
+ values={[
+ {label: 'MSTest', value: 'mstest'},
+ {label: 'NUnit', value: 'nunit'},
+ {label: 'xUnit', value: 'xunit'},
+ {label: 'xUnit v3', value: 'xunit-v3'},
+ ]
+}>
+<TabItem value="mstest">
+
```csharp
-class TestGitHubAPI : PageTest
+[TestClass]
+public class TestGitHubAPI : PageTest
{
[TestMethod]
public async Task LastCreatedIssueShouldBeFirstInTheList()
@@ -365,14 +1368,110 @@ class TestGitHubAPI : PageTest
}
```
+</TabItem>
+<TabItem value="nunit">
+
+```csharp
+[Parallelizable(ParallelScope.Self)]
+[TestFixture]
+public class TestGitHubAPI : PageTest
+{
+ [Test]
+ public async Task LastCreatedIssueShouldBeFirstInTheList()
+ {
+ var data = new Dictionary<string, string>
+ {
+ { "title", "[Feature] request 1" },
+ { "body", "Feature description" }
+ };
+ var newIssue = await Request.PostAsync("/repos/" + USER + "/" + REPO + "/issues", new() { DataObject = data });
+ await Expect(newIssue).ToBeOKAsync();
+
+ // When inheriting from 'PlaywrightTest' it only gives you a Playwright instance. To get a Page instance, either start
+ // a browser, context, and page manually or inherit from 'PageTest' which will launch it for you.
+ await Page.GotoAsync("https://github.com/" + USER + "/" + REPO + "/issues");
+ var firstIssue = Page.Locator("a[data-hovercard-type='issue']").First;
+ await Expect(firstIssue).ToHaveTextAsync("[Feature] request 1");
+ }
+}
+```
+
+</TabItem>
+<TabItem value="xunit">
+
+```csharp
+public class TestGitHubAPI : PageTest
+{
+ [Fact]
+ public async Task LastCreatedIssueShouldBeFirstInTheList()
+ {
+ var data = new Dictionary<string, string>
+ {
+ { "title", "[Feature] request 1" },
+ { "body", "Feature description" }
+ };
+ var newIssue = await Request.PostAsync("/repos/" + USER + "/" + REPO + "/issues", new() { DataObject = data });
+ await Expect(newIssue).ToBeOKAsync();
+
+ // When inheriting from 'PlaywrightTest' it only gives you a Playwright instance. To get a Page instance, either start
+ // a browser, context, and page manually or inherit from 'PageTest' which will launch it for you.
+ await Page.GotoAsync("https://github.com/" + USER + "/" + REPO + "/issues");
+ var firstIssue = Page.Locator("a[data-hovercard-type='issue']").First;
+ await Expect(firstIssue).ToHaveTextAsync("[Feature] request 1");
+ }
+}
+```
+
+</TabItem>
+<TabItem value="xunit-v3">
+
+```csharp
+public class TestGitHubAPI : PageTest
+{
+ [Fact]
+ public async Task LastCreatedIssueShouldBeFirstInTheList()
+ {
+ var data = new Dictionary<string, string>
+ {
+ { "title", "[Feature] request 1" },
+ { "body", "Feature description" }
+ };
+ var newIssue = await Request.PostAsync("/repos/" + USER + "/" + REPO + "/issues", new() { DataObject = data });
+ await Expect(newIssue).ToBeOKAsync();
+
+ // When inheriting from 'PlaywrightTest' it only gives you a Playwright instance. To get a Page instance, either start
+ // a browser, context, and page manually or inherit from 'PageTest' which will launch it for you.
+ await Page.GotoAsync("https://github.com/" + USER + "/" + REPO + "/issues");
+ var firstIssue = Page.Locator("a[data-hovercard-type='issue']").First;
+ await Expect(firstIssue).ToHaveTextAsync("[Feature] request 1");
+ }
+}
+```
+
+</TabItem>
+</Tabs>
+
## Check the server state after running user actions
The following test creates a new issue via user interface in the browser and then checks via API if
it was created:
+<Tabs
+ groupId="test-runners"
+ defaultValue="mstest"
+ values={[
+ {label: 'MSTest', value: 'mstest'},
+ {label: 'NUnit', value: 'nunit'},
+ {label: 'xUnit', value: 'xunit'},
+ {label: 'xUnit v3', value: 'xunit-v3'},
+ ]
+}>
+<TabItem value="mstest">
+
```csharp
// Make sure to extend from PageTest if you want to use the Page class.
-class GitHubTests : PageTest
+[TestClass]
+public class GitHubTests : PageTest
{
[TestMethod]
public async Task LastCreatedIssueShouldBeOnTheServer()
@@ -391,6 +1490,83 @@ class GitHubTests : PageTest
}
```
+</TabItem>
+<TabItem value="nunit">
+
+```csharp
+// Make sure to extend from PageTest if you want to use the Page class.
+[Parallelizable(ParallelScope.Self)]
+[TestFixture]
+public class GitHubTests : PageTest
+{
+ [Test]
+ public async Task LastCreatedIssueShouldBeOnTheServer()
+ {
+ await Page.GotoAsync("https://github.com/" + USER + "/" + REPO + "/issues");
+ await Page.Locator("text=New Issue").ClickAsync();
+ await Page.Locator("[aria-label='Title']").FillAsync("Bug report 1");
+ await Page.Locator("[aria-label='Comment body']").FillAsync("Bug description");
+ await Page.Locator("text=Submit new issue").ClickAsync();
+ var issueId = Page.Url.Substring(Page.Url.LastIndexOf('/'));
+
+ var newIssue = await Request.GetAsync("https://github.com/" + USER + "/" + REPO + "/issues/" + issueId);
+ await Expect(newIssue).ToBeOKAsync();
+ Assert.That(await newIssue.TextAsync(), Does.Contain("Bug report 1"));
+ }
+}
+```
+
+</TabItem>
+<TabItem value="xunit">
+
+```csharp
+// Make sure to extend from PageTest if you want to use the Page class.
+public class GitHubTests : PageTest
+{
+ [Fact]
+ public async Task LastCreatedIssueShouldBeOnTheServer()
+ {
+ await Page.GotoAsync("https://github.com/" + USER + "/" + REPO + "/issues");
+ await Page.Locator("text=New Issue").ClickAsync();
+ await Page.Locator("[aria-label='Title']").FillAsync("Bug report 1");
+ await Page.Locator("[aria-label='Comment body']").FillAsync("Bug description");
+ await Page.Locator("text=Submit new issue").ClickAsync();
+ var issueId = Page.Url.Substring(Page.Url.LastIndexOf('/'));
+
+ var newIssue = await Request.GetAsync("https://github.com/" + USER + "/" + REPO + "/issues/" + issueId);
+ await Expect(newIssue).ToBeOKAsync();
+ Assert.Contains("Bug report 1", await newIssue.TextAsync());
+ }
+}
+```
+
+</TabItem>
+<TabItem value="xunit-v3">
+
+```csharp
+// Make sure to extend from PageTest if you want to use the Page class.
+public class GitHubTests : PageTest
+{
+ [Fact]
+ public async Task LastCreatedIssueShouldBeOnTheServer()
+ {
+ await Page.GotoAsync("https://github.com/" + USER + "/" + REPO + "/issues");
+ await Page.Locator("text=New Issue").ClickAsync();
+ await Page.Locator("[aria-label='Title']").FillAsync("Bug report 1");
+ await Page.Locator("[aria-label='Comment body']").FillAsync("Bug description");
+ await Page.Locator("text=Submit new issue").ClickAsync();
+ var issueId = Page.Url.Substring(Page.Url.LastIndexOf('/'));
+
+ var newIssue = await Request.GetAsync("https://github.com/" + USER + "/" + REPO + "/issues/" + issueId);
+ await Expect(newIssue).ToBeOKAsync();
+ Assert.Contains("Bug report 1", await newIssue.TextAsync());
+ }
+}
+```
+
+</TabItem>
+</Tabs>
+
## Reuse authentication state
Web apps use cookie-based or token-based authentication, where authenticated
diff --git a/docs/src/webview2.md b/docs/src/webview2.md
index 6e8fc62b2f..2244e66a50 100644
--- a/docs/src/webview2.md
+++ b/docs/src/webview2.md
@@ -343,16 +343,29 @@ def test_webview2(page: Page):
expect(get_started).to_be_visible()
```
-```csharp
-// WebView2Test.cs
+### Test base class
+* langs: csharp
+
+<Tabs
+ groupId="test-runners"
+ defaultValue="mstest"
+ values={[
+ {label: 'MSTest', value: 'mstest'},
+ {label: 'NUnit', value: 'nunit'},
+ {label: 'xUnit', value: 'xunit'},
+ {label: 'xUnit v3', value: 'xunit-v3'},
+ ]
+}>
+<TabItem value="mstest">
+
+```csharp title="WebView2Test.cs"
using System.Diagnostics;
using Microsoft.Playwright;
using Microsoft.Playwright.MSTest;
namespace PlaywrightTests;
-[TestClass]
-public class ExampleTest : PlaywrightTest
+public class WebView2Test : PlaywrightTest
{
public IBrowser Browser { get; internal set; } = null!;
public IBrowserContext Context { get; internal set; } = null!;
@@ -408,8 +421,7 @@ public class ExampleTest : PlaywrightTest
}
```
-```csharp
-// UnitTest1.cs
+```csharp title="UnitTest1.cs"
using Microsoft.Playwright;
using Microsoft.Playwright.MSTest;
@@ -428,6 +440,265 @@ public class ExampleTest : WebView2Test
}
```
+</TabItem>
+<TabItem value="nunit">
+
+```csharp title="WebView2Test.cs"
+using System.Diagnostics;
+using Microsoft.Playwright;
+using Microsoft.Playwright.NUnit;
+using NUnit.Framework;
+
+namespace PlaywrightTests;
+
+public class WebView2Test : PlaywrightTest
+{
+ public IBrowser Browser { get; internal set; } = null!;
+ public IBrowserContext Context { get; internal set; } = null!;
+ public IPage Page { get; internal set; } = null!;
+ private Process? _webView2Process = null;
+ private string _userDataDir = null!;
+ private string _executablePath = Path.Join(Directory.GetCurrentDirectory(), @"..\..\..\..\webview2-app\bin\Debug\net8.0-windows\webview2.exe");
+
+ [SetUp]
+ public async Task BrowserTestSetUp()
+ {
+ var cdpPort = 10000 + WorkerIndex;
+ Assert.That(File.Exists(_executablePath), Is.True, "Make sure that the executable exists");
+ _userDataDir = Path.Join(Path.GetTempPath(), $"playwright-webview2-tests/user-data-dir-{WorkerIndex}");
+ // WebView2 does some lazy cleanups on shutdown so we can't clean it up after each test
+ if (Directory.Exists(_userDataDir))
+ {
+ Directory.Delete(_userDataDir, true);
+ }
+ _webView2Process = Process.Start(new ProcessStartInfo(_executablePath)
+ {
+ EnvironmentVariables =
+ {
+ ["WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS"] = $"--remote-debugging-port={cdpPort}",
+ ["WEBVIEW2_USER_DATA_FOLDER"] = _userDataDir,
+ },
+ RedirectStandardOutput = true,
+ });
+ while (!_webView2Process!.HasExited)
+ {
+ var output = await _webView2Process!.StandardOutput.ReadLineAsync();
+ if (_webView2Process!.HasExited)
+ {
+ throw new Exception("WebView2 process exited unexpectedly");
+ }
+ if (output != null && output.Contains("WebView2 initialized"))
+ {
+ break;
+ }
+ }
+ var cdpAddress = $"http://127.0.0.1:{cdpPort}";
+ Browser = await Playwright.Chromium.ConnectOverCDPAsync(cdpAddress);
+ Context = Browser.Contexts[0];
+ Page = Context.Pages[0];
+ }
+
+ [TearDown]
+ public async Task BrowserTestTearDown()
+ {
+ _webView2Process!.Kill(true);
+ await Browser.CloseAsync();
+ }
+}
+```
+
+```csharp title="UnitTest1.cs"
+using Microsoft.Playwright;
+using Microsoft.Playwright.NUnit;
+using NUnit.Framework;
+
+namespace PlaywrightTests;
+
+[Parallelizable(ParallelScope.Self)]
+[TestFixture]
+public class ExampleTest : WebView2Test
+{
+ [Test]
+ public async Task HomepageHasPlaywrightInTitleAndGetStartedLinkLinkingtoTheIntroPage()
+ {
+ await Page.GotoAsync("https://playwright.dev");
+ var getStarted = Page.GetByText("Get Started");
+ await Expect(getStarted).ToBeVisibleAsync();
+ }
+}
+```
+
+</TabItem>
+<TabItem value="xunit">
+
+```csharp title="WebView2Test.cs"
+using System.Diagnostics;
+using Microsoft.Playwright;
+using Microsoft.Playwright.Xunit;
+
+namespace PlaywrightTests;
+
+public class WebView2Test : PlaywrightTest
+{
+ public IBrowser Browser { get; internal set; } = null!;
+ public IBrowserContext Context { get; internal set; } = null!;
+ public IPage Page { get; internal set; } = null!;
+ private Process? _webView2Process = null;
+ private string _userDataDir = null!;
+ private string _executablePath = Path.Join(Directory.GetCurrentDirectory(), @"..\..\..\..\webview2-app\bin\Debug\net8.0-windows\webview2.exe");
+
+ public override async Task InitializeAsync()
+ {
+ await base.InitializeAsync();
+ var cdpPort = 10000 + WorkerIndex;
+ Assert.True(File.Exists(_executablePath), "Make sure that the executable exists");
+ _userDataDir = Path.Join(Path.GetTempPath(), $"playwright-webview2-tests/user-data-dir-{WorkerIndex}");
+ // WebView2 does some lazy cleanups on shutdown so we can't clean it up after each test
+ if (Directory.Exists(_userDataDir))
+ {
+ Directory.Delete(_userDataDir, true);
+ }
+ _webView2Process = Process.Start(new ProcessStartInfo(_executablePath)
+ {
+ EnvironmentVariables =
+ {
+ ["WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS"] = $"--remote-debugging-port={cdpPort}",
+ ["WEBVIEW2_USER_DATA_FOLDER"] = _userDataDir,
+ },
+ RedirectStandardOutput = true,
+ });
+ while (!_webView2Process!.HasExited)
+ {
+ var output = await _webView2Process!.StandardOutput.ReadLineAsync();
+ if (_webView2Process!.HasExited)
+ {
+ throw new Exception("WebView2 process exited unexpectedly");
+ }
+ if (output != null && output.Contains("WebView2 initialized"))
+ {
+ break;
+ }
+ }
+ var cdpAddress = $"http://127.0.0.1:{cdpPort}";
+ Browser = await Playwright.Chromium.ConnectOverCDPAsync(cdpAddress);
+ Context = Browser.Contexts[0];
+ Page = Context.Pages[0];
+ }
+
+ public override async Task DisposeAsync()
+ {
+ _webView2Process!.Kill(true);
+ await Browser.CloseAsync();
+ await base.DisposeAsync();
+ }
+}
+```
+
+```csharp title="UnitTest1.cs"
+using Microsoft.Playwright;
+using Microsoft.Playwright.Xunit;
+
+namespace PlaywrightTests;
+
+public class ExampleTest : WebView2Test
+{
+ [Fact]
+ public async Task HomepageHasPlaywrightInTitleAndGetStartedLinkLinkingtoTheIntroPage()
+ {
+ await Page.GotoAsync("https://playwright.dev");
+ var getStarted = Page.GetByText("Get Started");
+ await Expect(getStarted).ToBeVisibleAsync();
+ }
+}
+```
+
+</TabItem>
+<TabItem value="xunit-v3">
+
+```csharp title="WebView2Test.cs"
+using System.Diagnostics;
+using Microsoft.Playwright;
+using Microsoft.Playwright.Xunit.v3;
+
+namespace PlaywrightTests;
+
+public class WebView2Test : PlaywrightTest
+{
+ public IBrowser Browser { get; internal set; } = null!;
+ public IBrowserContext Context { get; internal set; } = null!;
+ public IPage Page { get; internal set; } = null!;
+ private Process? _webView2Process = null;
+ private string _userDataDir = null!;
+ private string _executablePath = Path.Join(Directory.GetCurrentDirectory(), @"..\..\..\..\webview2-app\bin\Debug\net8.0-windows\webview2.exe");
+
+ public override async Task InitializeAsync()
+ {
+ await base.InitializeAsync();
+ var cdpPort = 10000 + WorkerIndex;
+ Assert.True(File.Exists(_executablePath), "Make sure that the executable exists");
+ _userDataDir = Path.Join(Path.GetTempPath(), $"playwright-webview2-tests/user-data-dir-{WorkerIndex}");
+ // WebView2 does some lazy cleanups on shutdown so we can't clean it up after each test
+ if (Directory.Exists(_userDataDir))
+ {
+ Directory.Delete(_userDataDir, true);
+ }
+ _webView2Process = Process.Start(new ProcessStartInfo(_executablePath)
+ {
+ EnvironmentVariables =
+ {
+ ["WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS"] = $"--remote-debugging-port={cdpPort}",
+ ["WEBVIEW2_USER_DATA_FOLDER"] = _userDataDir,
+ },
+ RedirectStandardOutput = true,
+ });
+ while (!_webView2Process!.HasExited)
+ {
+ var output = await _webView2Process!.StandardOutput.ReadLineAsync();
+ if (_webView2Process!.HasExited)
+ {
+ throw new Exception("WebView2 process exited unexpectedly");
+ }
+ if (output != null && output.Contains("WebView2 initialized"))
+ {
+ break;
+ }
+ }
+ var cdpAddress = $"http://127.0.0.1:{cdpPort}";
+ Browser = await Playwright.Chromium.ConnectOverCDPAsync(cdpAddress);
+ Context = Browser.Contexts[0];
+ Page = Context.Pages[0];
+ }
+
+ public override async Task DisposeAsync()
+ {
+ _webView2Process!.Kill(true);
+ await Browser.CloseAsync();
+ await base.DisposeAsync();
+ }
+}
+```
+
+```csharp title="UnitTest1.cs"
+using Microsoft.Playwright;
+using Microsoft.Playwright.Xunit.v3;
+
+namespace PlaywrightTests;
+
+public class ExampleTest : WebView2Test
+{
+ [Fact]
+ public async Task HomepageHasPlaywrightInTitleAndGetStartedLinkLinkingtoTheIntroPage()
+ {
+ await Page.GotoAsync("https://playwright.dev");
+ var getStarted = Page.GetByText("Get Started");
+ await Expect(getStarted).ToBeVisibleAsync();
+ }
+}
+```
+
+</TabItem>
+</Tabs>
+
## Debugging
Inside your webview2 control, you can just right-click to open the context menu and select "Inspect" to open the DevTools or press <kbd>F12</kbd>. You can also use the [WebView2.CoreWebView2.OpenDevToolsWindow](https://learn.microsoft.com/en-us/dotnet/api/microsoft.web.webview2.core.corewebview2.opendevtoolswindow?view=webview2-dotnet-1.0.1462.37) method to open the DevTools programmatically.