Getting Started with Playwright using Visual Studio 2022/C# and NUnit
1. Introduction
In this walkthrough, we use Visual Studio 2022 Community Edition with C# and NUnit to get started with Playwright. We develop a simple example to introduce the basic features of Playwright, using a Windows 11 machine. The same example should work on MacOS and Linux machines as well.
2. Background
When it comes to automated web testing, automation engineers are faced with a myriad of tool choices. One tool that has long dominated the automation landscape is Selenium. Recently, Playwright has also been gaining popularity, which leads nicely to the topic of this article. For newcomers to the field of test automation or those transitioning from the Selenium family, this article offers a gentle introduction to Playwright.
3. Install Playwright
Visual Studio manages many components essential for Playwright development. However, some Playwright commands, like the code generator – CodeGen, which we will be using later to record our test case, depend on the Playwright CLI library. Therefore, it is recommended to install the following components on our machine.
3.1 Install Node.js
Let us verify that node.js is installed on our machine.
3.2 Install Playwright Browsers
Let us install the Playwright browsers on our machine. By default, Playwright installs the following 3 ?browsers: Chromium, Firefox, and Webkit.
npx playwright install
4. Install Visual Studio
In this section, we provide the steps for installing visual studio, creating an NUnit, and installing NuGet packages for Playwright.
4.1 Install Visual Studio 2022 (Community edition)
For those of you who are new to the .NET environment, start by installing Visual Studio 2022 Community Edition from https://visualstudio.microsoft.com/vs/community/.
Once the installation is complete, configure your environment to use C#. If you already have any version of Visual Studio installed on your machine, you are all set!
4.2 Create a new folder for the test project
?To follow along, let us create a folder called “PlaywrightDemo” on our machine to host the playwright test project.
4.3 Open Visual Studio and create a new NUnit project
To create the test project, start Visual Studio and create a new project using the NUnit template. The basic structure of the generated project should include a single test case called 'UnitTest1.cs', as shown in Figure 1.
4.4 Install NuGet packages for Playwright
Next,? install the NuGet packages for Playwright. To do so, right-click on the test project (PlaywrightDemo) and select “Manage NuGet Packages…”. Once the NuGet Package Manager window opens, search for the following packages, shown in Figure 2, ?and install them.
4.5 Create a test case and run it manually
Before embarking on the automation phase, let us first familiarize ourselves with the steps of the test case slated for automation. The primary objective of this test case is to validate the functionality of a given scenario, by manually executing the steps. The complete steps are shown below, ?in Table 1.
We selected this site due to its comprehensive set of features, mirroring those of a fully operational ecommerce platform.
5. Code Generation
Playwright offers a GUI called Codegen to record test cases from start to finish, including various types of assertions such as assert visibility, assert text, and assert value. We found Codegen to be a great tool for automating test cases due to its visual and intuitive interface. Additionally, it can serve as a documentation tool for manual testers to capture the steps of the test case, enhancing communication between manual testers, developers, and automation testers.
领英推荐
We illustrate the features of Codegen by recording the sample test provided earlier and generating code for C# using NUnit.
6. Recording Tests - Codegen
To record tests in Playwright, we execute the following command in PowerShell window.
This command starts the recorder and opens 2 windows, (1) a Playwright Inspector window, as shown in Figure 4, ?and (2) a browser window showing the home page of the site, as shown in Figure 5.
Note that when Codegen (more specifically, the Playwright Inspector) starts, Node.js is selected by default. So, if you are using Node.js, you are good to go. In our case, we are using NUnit, so make sure to select that option from the dropdown.
The browser window displays five options at the top. If these options are not visible, ensure that you have the latest Playwright version installed by running the following command.
npx playwright --version
6.1 Playwright Code Generator Actions
These actions help users creation and validate tests with specific interactions and assertions.
We are now ready to record the test case by interacting with the browser. The tool will capture our interactions and generate the code in the “Inspector” window.
Here is the code that we generated for the test case above.
using Microsoft.Playwright.NUnit;
using Microsoft.Playwright;
using System.Text.RegularExpressions;
namespace PlaywrightDemoTests
{
[Parallelizable(ParallelScope.Self)]
[TestFixture]
public class PurchaseNotebooks_Asus : PageTest
{
// The following code is generated by Playwright's Codegen
// using a terminal window command.
// "npx playwright https://demo.nopcommerce.com/"
[Test]
public async Task PurchaseAsusI7NotebookWith16GBRam ()
{
await Page.GotoAsync("https://demo.nopcommerce.com/");
await Page.GetByRole(AriaRole.Link, new() { Name = "Computers" }).ClickAsync();
await Page.GetByRole(AriaRole.Link, new() { Name = "Notebooks" }).First.ClickAsync();
await Page.GetByLabel("Intel Core i7").CheckAsync();
await Page.GetByLabel("16 GB").CheckAsync();
await Page.GetByRole(AriaRole.Link, new() { Name = "Asus N551JK-XO076H Laptop", Exact = true }).ClickAsync();
await Page.Locator("#add-to-cart-button-5").ClickAsync();
await Page.GetByRole(AriaRole.Link, new() { Name = "Shopping cart (1)" }).ClickAsync();
await Expect(Page.Locator("#shopping-cart-form")).ToContainTextAsync("$1,500.00");
await Page.GetByLabel("I agree with the terms of").CheckAsync();
await Page.GetByRole(AriaRole.Button, new() { Name = "Checkout" }).ClickAsync();;
}
}
}
The generated code is verbose, hard to read, and uses many hard-coded values, but it is a good start. It works out of the box, and it gives us the freedom to improve the structure and readability of our tests.
7. Executing the test case
Once the code is generated, simply copy and paste it into your test case, and run the test. The test should pass, but you will notice that there is no browser. Bu default, the test runs in headless mode. In order to see the browser, we need to create a file called “Headless.runsettings”. Actually, any name with the extension (.runsettings) should work.
Here are the steps to create this file.
1.?? Right-click on the project name in the solution
2.?? Select Add à new item
3.?? Select XMLFile.xml (change the file to “Headless.runsettings”)
(Any name with the extension (.runsettings) should work.)
4.?? Paste the following code
5.?? From the Test menu in Visual Studio, select
Test -> Configure Run Setting -> Select Solution Wide runsettings File, then select the xml file we just created (i.e., Headless.runsettings)
6.?? Build the solution and run the test. This time, it should run with a visible browser.
You can find the complete solution on GitHub. Remember, the best way to learn is to practice. Happy testing!
8. Conclusion
Playwright is a great tool for end-to-end testing, offering testers the ability to automatically generate code, ready for execution. It offers a good starting point for automation projects. Beyond its testing capabilities, Playwright can also serve as a communication platform among manual testers, automation specialists, developers, and other stakeholders. In this article, we demonstrated its use with C# and the NUnit framework. However, Playwright was designed to support various languages and testing frameworks, out of the box, providing flexibility for a wide range of testing scenarios.
Driving Quality & Efficiency through Leadership and Automation
8 个月Exactly what I need it!