Playwright .NET:存储复用storageState上下文及PageTest适配问题
问题描述
- 刚接触Playwright C#版本,此前在TypeScript中多次实现会话状态的存储与复用,但在.NET版本遇到卡点
- 使用NUnit框架,BaseTest继承自
PageTest,已在OneTimeSetUp中成功将会话状态保存到../../../playwright/.auth/state.json文件 - 尝试在
SetUp中调用NewContextAsync加载存储状态,但PageTest没有该方法,编译器报错 - 需求:所有测试默认复用带会话状态的上下文,仅特殊场景使用全新上下文
- 额外问题:追踪配置代码顺序错误,未初始化
Context就调用Tracing.StartAsync
解决方案
一、解决会话状态复用问题(PageTest无法调用NewContextAsync)
PageTest是Playwright提供的简化测试类,默认自动创建Context和Page。要自定义上下文,需要重写CreateContextAsync方法,而非在SetUp中手动创建。
1. 全局默认复用会话状态
在BaseTest中重写CreateContextAsync,指定加载已保存的存储状态,所有继承该基类的测试都会自动复用会话:
public class BaseTest : PageTest { private readonly string _storageStatePath = "../../../playwright/.auth/state.json"; [OneTimeSetUp] public async Task OneTimeSetUp() { // 这里是你已实现的会话状态保存逻辑,比如登录后导出状态 // await Page.Context.StorageStateAsync(new() { Path = _storageStatePath }); } protected override async Task<IBrowserContext> CreateContextAsync() { // 创建上下文时自动加载已保存的会话状态 var contextOptions = new BrowserNewContextOptions { StorageStatePath = _storageStatePath }; return await Browser.NewContextAsync(contextOptions); } }
2. 特殊场景使用全新上下文
如果某类/某条测试需要全新上下文,只需在对应测试类中再次重写CreateContextAsync,不指定存储状态即可:
[TestFixture] public class FreshContextTests : BaseTest { protected override async Task<IBrowserContext> CreateContextAsync() { // 创建不带会话状态的全新上下文 return await Browser.NewContextAsync(); } [Test] public async Task TestWithoutReusingSession() { // 当前测试的Page会使用全新上下文 await Page.GotoAsync("https://example.com"); // ...测试逻辑 } }
二、修复追踪配置顺序问题
你的代码顺序错误,必须先初始化Playwright、Browser、Context,再启动追踪(Context.Tracing.StartAsync依赖已创建的Context)。
自定义管理Playwright/Browser的正确顺序
// 1. 先初始化Playwright和Browser Playwright = await Microsoft.Playwright.Playwright.CreateAsync(); Browser = await Playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions { Headless = false }); // 2. 创建带会话状态的Context Context = await Browser.NewContextAsync(new BrowserNewContextOptions { StorageStatePath = _storageStatePath }); // 3. 启动追踪(此时Context已初始化) await Context.Tracing.StartAsync(new() { Title = TestContext.CurrentContext.Test.ClassName + "." + TestContext.CurrentContext.Test.Name, Screenshots = true, Snapshots = true, Sources = true, }); // 4. 创建Page Page = await Context.NewPageAsync();
基于PageTest的追踪配置
如果使用PageTest自动管理Context,可在SetUp中直接获取当前Context启动追踪:
[SetUp] public async Task Setup() { await Context.Tracing.StartAsync(new() { Title = TestContext.CurrentContext.Test.ClassName + "." + TestContext.CurrentContext.Test.Name, Screenshots = true, Snapshots = true, Sources = true, }); } [TearDown] public async Task TearDown() { // 测试结束后保存追踪文件 await Context.Tracing.StopAsync(new() { Path = $"../../../playwright/traces/{TestContext.CurrentContext.Test.Name}.zip" }); }
内容的提问来源于stack exchange,提问作者msmith1114
相关产品推荐
相关产品推荐

