使用Selenium测试ASP.NET Core 6 MVC应用遇连接拒绝问题求助
解决方案
1. 修复Program类的可访问性
ASP.NET Core 6+顶级语句生成的Program类默认是internal,测试项目无法直接访问。在Web项目的Program.cs末尾添加一行:
public partial class Program;
2. 重构TestContactBookApp实现
当前实现嵌套WebApplicationFactory会导致启动逻辑混乱,正确做法是直接继承并自定义配置:
namespace ContactBook.Tests.Common { public class TestContactBookApp : WebApplicationFactory<Program> { private readonly TestDb _testDb; private readonly string _appContentRoot; public TestContactBookApp(TestDb testDb, string appContentRoot) { _testDb = testDb; _appContentRoot = appContentRoot; } protected override void ConfigureWebHost(IWebHostBuilder webHostBuilder) { webHostBuilder.UseContentRoot(_appContentRoot); webHostBuilder.ConfigureServices(services => { // 移除原有DbContext配置 var descriptor = services.SingleOrDefault(d => d.ServiceType == typeof(DbContextOptions<ContactBookDbContext>)); if (descriptor != null) { services.Remove(descriptor); } // 替换为测试数据库 services.AddDbContext<ContactBookDbContext>(_ => _.UseSqlServer(_testDb.CreateDbContext().Database.GetConnectionString())); }); // 指定随机端口启动真实HTTP服务器(Selenium需要真实网络端口) webHostBuilder.UseUrls("http://127.0.0.1:0"); } } }
3. 修正Selenium测试基类的地址获取逻辑
之前用HttpClient.BaseAddress是内存客户端地址,Selenium需要访问真实启动的服务器地址,通过ServerAddressesFeature获取:
namespace ContactBook.WebAPI.SeleniumTests { public class SeleniumTestsBase { protected TestDb testDb; protected IWebDriver driver; protected TestContactBookApp testContactBookApp; protected string baseUrl; protected string username; protected string password; protected string phoneNumber; [OneTimeSetUp] public void OneTimeSetUpBase() { testDb = new TestDb(); testContactBookApp = new TestContactBookApp(testDb, "../../../../ContactBook.WebApp"); // 启动服务器并获取真实访问地址 var server = testContactBookApp.Server; server.Start(); var addresses = server.Features.Get<IServerAddressesFeature>(); baseUrl = addresses.Addresses.First(); username = $"user{DateTime.Now.Ticks.ToString()[10..]}"; password = $"pass{DateTime.Now.Ticks.ToString()[10..]}"; phoneNumber = "+359886183166"; ChromeOptions chromeOptions = new ChromeOptions(); if (!Debugger.IsAttached) chromeOptions.AddArguments("headless=new"); // 新版无头模式兼容性更好 chromeOptions.AddArguments("--start-maximized"); driver = new ChromeDriver(chromeOptions); driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5); } [OneTimeTearDown] public void OneTimeTearDownBase() { driver.Quit(); testContactBookApp.Dispose(); } } }
4. 解决Configure方法找不到的错误
这个错误是因为误用IHostBuilder配置,ASP.NET Core 6+ Web应用需用IWebHostBuilder(即上面重构后的方式),同时确保已添加public partial class Program;让测试项目能访问Program类。
关键注意点
- 不要嵌套
WebApplicationFactory,直接继承并配置才能保证服务器正确启动 - Selenium必须访问真实网络端口,不能用内存客户端的地址
- 新版Chrome推荐使用
headless=new参数代替旧的headless,避免兼容性问题
内容的提问来源于stack exchange,提问作者vassdeniss
相关产品推荐
相关产品推荐

