Reputation: 876
I'm using Playwright with C# to automate tests for my application. The application requires a login step before executing any test. My goal is to:
Currently, I use TestInitialize
for the login logic, but this means I have to run each test method individually. If I run all methods together, the login logic is executed before every test, which I want to avoid.
I tried using ClassInitialize
for the login logic, but it didn't work as ClassInitialize
doesn't seem to support Playwright's asynchronous methods.
ClassInitialize
, but I couldn't use async/await in that method.TestInitialize
, but it forces the login logic to execute before every test method.Here’s a simplified version of my test setup:
using Microsoft.Playwright;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AutomationTestRuns
{
public abstract class BaseTest : PageTest
{
public override BrowserNewContextOptions ContextOptions()
{
return new BrowserNewContextOptions
{
ViewportSize = ViewportSize.NoViewport,
StorageStatePath = "state.json",
};
}
[TestInitialize]
public async Task Startup()
{
Page.SetDefaultTimeout(30000);
await Page.GotoAsync("https://practice.expandtesting.com/login");
await Page.Locator("#username").FillAsync("practice");
await Page.Locator("#password").FillAsync("SuperSecretPassword!");
await Page.Locator("xpath=//button[normalize-space()='Login']").ClickAsync();
}
[TestCleanup]
public async Task Cleanup()
{
await Page.WaitForTimeoutAsync(5000);
if (Page != null) await Page.CloseAsync();
if (Context != null) await Context.CloseAsync();
if (Browser != null) await Browser.CloseAsync();
}
}
}
namespace AutomationTestRuns
{
[TestClass]
public class TestClass1 : BaseTest
{
[TestMethod]
public async Task TestClass1_Method1()
{
await Page.WaitForURLAsync("https://practice.expandtesting.com/secure");
var h1 = Page.Locator("xpath=//h1[normalize-space()='Secure Area']");
Assert.IsNotNull(h1);
}
[TestMethod]
public async Task TestClass1_Method2()
{
await Page.WaitForURLAsync("https://practice.expandtesting.com/secure");
var h3 = Page.Locator("xpath=//h1[normalize-space()='Hi, practice!']");
Assert.IsNotNull(h3);
}
}
}
TestClass1
, and close the browser only after the last test method finishes.From I run the test class from the test explorer
Any help or guidance would be greatly appreciated.
Upvotes: 0
Views: 49