我试图通过使用来自xUnit和AspNetCore.TestHost的调试在本地运行Playwright,即使当我调用 API 端点时调用成功,SPA 页面也没有加载。
有什么我应该做更多的改变WebApplicationFactory
吗?
到目前为止,我已经尝试过这种方法:
CustomWebApplicationFactory.cs
public class CustomWebApplicationFactory : WebApplicationFactory<Startup>
{
protected override IHostBuilder CreateHostBuilder()
{
return new HostBuilder()
.ConfigureHostConfiguration(config =>
{
// Make UseStaticWebAssets work
var applicationPath = typeof(Startup).Assembly.Location;
var applicationDirectory = Path.GetDirectoryName(applicationPath);
var name = Path.ChangeExtension(applicationPath, ".StaticWebAssets.xml");
var inMemoryConfiguration = new Dictionary<string, string>
{
[WebHostDefaults.StaticWebAssetsKey] = name,
};
config.AddInMemoryCollection(inMemoryConfiguration);
})
.ConfigureWebHost(webHostBuilder => webHostBuilder
.UseKestrel()
.UseSolutionRelativeContentRoot(typeof(Startup).Assembly.GetName().Name)
.UseStaticWebAssets()
.UseStartup<Startup>());
}
}
PlaywrightFixture.cs
public class PlaywrightFixture
{
public PlaywrightFixture()
{
this.Playwright = Microsoft.Playwright.Playwright.CreateAsync().GetAwaiter().GetResult();
var options = new BrowserTypeLaunchOptions
{
Headless = false,
};
this.Browser = this.Playwright.Chromium.LaunchAsync(options).GetAwaiter().GetResult();
}
private IPlaywright Playwright { get; set; }
public IBrowser Browser { get; private set; }
}
单元测试1.cs
public class UnitTest1 : IClassFixture<CustomWebApplicationFactory>, IClassFixture<PlaywrightFixture>
{
private readonly HttpClient _client;
private readonly PlaywrightFixture _playwrightFixture;
private readonly CustomWebApplicationFactory _factory;
public UnitTest1(CustomWebApplicationFactory factory, PlaywrightFixture playwrightFixture)
{
_client = factory?.CreateClient() ?? throw new ArgumentNullException(nameof(factory));
_factory = factory ?? throw new ArgumentNullException(nameof(factory));
_playwrightFixture = playwrightFixture ?? throw new ArgumentNullException(nameof(playwrightFixture));
}
[Fact]
public async Task Test1()
{
var apiCallSimulation = await _client.GetAsync(@"\WeatherForecast");
var contentResult = await apiCallSimulation.Content.ReadAsStringAsync();
var page = await _playwrightFixture.Browser.NewPageAsync();
var result = await page.GotoAsync($"https://localhost:5001");
}
}
收到 200 并呼叫控制器,apiCallSimulation
但如果我尝试访问链接,我将无法访问。
有没有办法实现在本地运行测试?我知道有手动启动项目并提供 url 的解决方案,但我想在集成测试中这样做。
我想到了另一个使用 Pragma 标记的想法,如果正在开发中运行dotnet .dll
,但我可能会遇到带有 CI/CD 的 Azure DevOps 问题