这看起来像是我们在剧作家敏锐存储库中收到的一个问题的“重复”。
为了完整起见,我将在此处添加相同的代码。我假设这是关于在单元测试中运行 Playwright Sharp 的。具体来说,我为此使用 Xunit。我们在 Playwright Sharp 测试中使用相同的方法。
首先,如果要在测试中重用对象,则定义 aaFixture
和 a 。这里有更多关于它的文章。Collection
Browser
public class BrowserTestFixture : IAsyncLifetime
{
public IPlaywright PlaywrightContext { get; private set; }
public IChromiumBrowser Browser { get; private set; }
public async Task InitializeAsync()
{
this.PlaywrightContext = await Playwright.CreateAsync();
this.Browser = await this.PlaywrightContext.Chromium.LaunchAsync(headless: false);
}
public async Task DisposeAsync()
{
PlaywrightContext?.Dispose();
}
}
[CollectionDefinition("Browser Collection")]
public class BrowserCollection : ICollectionFixture<BrowserTestFixture>
{
// This class has no code, and is never created. Its purpose is simply
// to be the place to apply [CollectionDefinition] and all the
// ICollectionFixture<> interfaces.
}
此时,您的测试可以通过Fixture
在构造函数中包含该引用来重用这些对象。我使用的示例在这里:
public class UnitTest1 : IClassFixture<BrowserTestFixture>
{
private readonly BrowserTestFixture browserTestFixture;
public UnitTest1(BrowserTestFixture browserTestFixture)
{
this.browserTestFixture = browserTestFixture;
}
[Fact]
public async Task HeadlineIsThere()
{
var page = await browserTestFixture.Browser.NewPageAsync();
await page.GoToAsync("https://www.github.com");
var content = await page.GetTextContentAsync("h1");
Assert.Equal("...", content);
}
[Fact]
public async Task CookieConsentDialogIsShownAndDissmisable()
{
var page = await browserTestFixture.Browser.NewPageAsync();
await page.GoToAsync("https://www.github.com");
var cookieDialogContents = await page.GetTextContentAsync(".cc-message");
Assert.True(!string.IsNullOrEmpty(cookieDialogContents));
await page.ClickAsync("[aria-label='dismiss cookie message']");
// ...
}
}
现在,我明确希望IPage
每次都创建一个新对象,但如果您坚持重复使用/共享它,您可以调整示例,即提供一个PageTestFixture
.