我试图让E2E/UI测试(selenium,剧作家)与我的单元测试框架一起工作。
使用MSTest和WebApplicationFactory从我的单元测试中派生出一个“真正的服务器”的基本思想。这样做的原因只是为了避免为了测试而部署/发布我的应用程序(我想这可以通过使用容器等来完成,遗憾的是。我不允许使用容器)。我还认为,这样做将是一种“整洁”的方式来嘲弄任何调用外部服务的代码,并能够为这些外部调用创建多个不同场景的测试。
我在网上搜索了一种这样做的方法,但我所能找到的只是关于如何在以前的.Net版本(2.1-5)中这样做的文章,但是自从.Net 6之后,“启动仪式”代码已经改变了,现在标准的方法是使用最小的API。
这是Scott.H的一篇博客文章,他基本上是在做我计划做的事情,但是使用.Net 2.1:https://www.hanselman.com/blog/real-browser-integration-testing-with-selenium-standalone-chrome-and-aspnet-core-21
到目前为止,我所做的是创建一个从WebApplicationFactory继承的自定义类。
基本上:
class MyAppFactory : WebApplicationFactory<Program> {
}我可以用它来进行集成测试。但是..。在使用该类时初始化的服务器不接受http调用,因此我无法使用web浏览器访问该服务器,selenium也不能。
我试着跟踪史考特的博客文章。但出于某种原因:
protected override TestServer CreateServer(IWebHostBuilder builder)从来不叫..。(不确定这是否需要最少的API和.Net 6来完成)。
是否有人能够使用WebApplicationFactory和.Net 6最小API在内存中划分一个接受http调用的“实际服务器”?
发布于 2022-05-17 19:15:20
在迁移到.NET 6时,我遇到了同样的问题,并找到了解决方案,这要归功于来自Marius的博客帖子。
步骤:
Program.cs文件中有程序定义var builder = WebApplication.CreateBuilder(args);
// adds services to the container
builder.Services.AddRazorPages();
var app = builder.Build();
// configures the HTTP request pipeline
app.UseExceptionHandler("/Error");
app.UseHsts();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapRazorPages();
app.Run();
public partial class Program { }WebApplicationFactoryFixture (示例)public class WebApplicationFactoryFixture<TEntryPoint> : WebApplicationFactory<TEntryPoint>
where TEntryPoint : class
{
public string HostUrl { get; set; } = "https://localhost:5001"; // we can use any free port
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.UseUrls(HostUrl);
}
protected override IHost CreateHost(IHostBuilder builder)
{
var dummyHost = builder.Build();
builder.ConfigureWebHost(webHostBuilder => webHostBuilder.UseKestrel());
var host = builder.Build();
host.Start();
return dummyHost;
}
}public class SmokeSeleniumTest : IClassFixture<WebApplicationFactoryFixture<Program>>
{
private readonly string _webUrl = "https://localhost:7112";
public SmokeSeleniumTest(WebApplicationFactoryFixture<Program> factory)
{
factory.HostUrl = _webUrl;
factory.CreateDefaultClient();
var chromeOptions = new ChromeOptions();
// ...
WebDriver = new ChromeDriver(chromeDriverLocation, chromeOptions);
}
protected IWebDriver WebDriver { get; }
[Theory]
[InlineData("/", "Welcome")]
[InlineData("/Index", "Welcome")]
[InlineData("/Privacy", "Privacy Policy")]
[InlineData("/Error", "Error.")]
public void Get_EndpointsReturnSuccessAndCorrectContentType(string url, string expected)
{
// Arrange & Act
WebDriver.Navigate().GoToUrl($"{_webUrl}{url}");
// Assert
WebDriver.FindElement(By.TagName("h1"), 30);
WebDriver.FindElement(By.TagName("h1")).Text.Should().Contain(expected);
}
}它起作用了!
发布于 2022-04-25 10:04:05
看起来您需要显式地调用CreateServer。这个博客文章展示了作者在从2.2迁移到3.1时是如何解决这个问题的--我不知道.NET 6中是否有更好的解决方案,但这至少可以解决您的问题。
https://stackoverflow.com/questions/71541576
复制相似问题