unit-testing - 为什么单元测试不能连接到 websocket

标签 unit-testing asp.net-core websocket

更新:我上传了一个 repo - https://github.com/mrpmorris/CannotIntegrationTestWebApp/blob/master/TestProject1/UnitTest1.cs

我有一个网络服务器,可以同时处理 HTTPS 和 WebSocket 请求。当我运行该应用程序时,我能够连接到 postman 并向 HTTPS://localhost:8080 和 WSS://localhost:8080/game-server 发出请求

using Gambit.ApplicationLayer;
using Gambit.GameServer.Configuration;
using Gambit.GameServer.UseCases;

namespace Gambit.GameServer;

public class Program
{
    public static async Task Main(string[] args)
    {
        WebApplication app = BuildApp(args);
        await RunAppAsync(app);
    }

    public static WebApplication BuildApp(string[] args, Action<WebApplicationBuilder>? configure = null)
    {
        WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
        IServiceCollection services = builder.Services;
        IConfiguration configuration = builder.Configuration;
        IWebHostEnvironment environment = builder.Environment;

        services.AddControllers();
        services.AddLogging(opts =>
        {
            opts.ClearProviders();
            opts.AddConfiguration(configuration.GetSection("Logging"));
            opts.AddDebug();
            opts.AddEventSourceLogger();
#if DEBUG
            if (environment.IsDevelopment())
                opts.AddConsole();
#endif
        });
        services.Configure<GameServerOptions>(configuration.GetSection("GameServer"));
        services.AddApplicationServices(configuration);

        configure?.Invoke(builder);
        WebApplication app = builder.Build();
        return app;
    }

    public static async Task RunAppAsync(WebApplication app)
    {
        app.MapGet("/", () => "Gambit.Server.API is running");
        app.AddUserUseCases();
        app.AddGameUseCases();
        app.MapControllers();
        app.UseWebSockets();
        await app.RunAsync();
    }
}

当我运行我的单元测试时,我使用相同的代码来创建和运行服务器(每次测试运行一次)我的测试能够发出 HTTPS 请求但不能通过 WebSocket 连接。当我尝试时,出现 404 错误。我在 PostMan 中也有同样的经历。

    static IntegrationTestsServer()
    {
        ConfigureMocks();
        Environment.SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", "IntegrationTesting");
        var app = Program.BuildApp(Array.Empty<string>(), builder =>
        {
            builder.WebHost.UseSetting("urls", "https://localhost:8080");
        });

        Configuration = app.Services.GetRequiredService<IConfiguration>();
        GameServerOptions = app.Services.GetRequiredService<IOptions<GameServerOptions>>();
        var dbContextOptions = app.Services.GetRequiredService<DbContextOptions<ApplicationDbContext>>();
        using var dbContext = new ApplicationDbContext(dbContextOptions);
        dbContext.Database.EnsureDeleted();
        dbContext.Database.EnsureCreated();
        HttpClient = new HttpClient { BaseAddress = new Uri("https://localhost:8080") };
        _ = Program.RunAppAsync(app);
    }

我什至可以在 ClientWebSocket 失败之前立即执行成功的 HttpClient.GetAsync("https://localhost:8080")

System.Net.WebSockets.WebSocketException:当预期状态代码为“101”时,服务器返回了状态代码“404”。

有人知道为什么会这样吗?

最佳答案

在发送到 WebApplication.CreateBuilder 的 WebApplicationOptions 中设置 ApplicationName

WebApplication.CreateBuilder
(
  new WebApplicationOptions
  {
    ApplicationName = typeof(Gambit.GameServer.Program).Assembly.GetName().Name // <== 
  }
);

现在它可以在从测试运行时找到您的 manifest 文件。

请参阅以下博客文章,了解更多关于我是如何想出来的背景故事。

https://thefreezeteam.com/posts/StevenTCramer/2022/08/25/runwebserverintest

关于unit-testing - 为什么单元测试不能连接到 websocket,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72928110/

相关文章:

jquery - 控制 QUnit 测试顺序

python - Django 测试 : how to specify the apps whose databases I want to use?

java - 如何在 TestNG 中使用 Mockito 模拟 jdbc 连接和 resultSet

spring - 使用 Spring 踩踏 websocket 和 sockJS 消息丢失

java - 如何使用 Junit 测试在数据库中插入记录的 void 方法?

c# - 将 Base64 图像从 View 发送到 ASP.NET Controller

asp.net-core - .NET Core + Openiddict InvalidCastException

c# - ASP.NET Core 过滤器内的 ViewBag

go - 尝试 Websocket 连接时出现意外响应代码 200

javascript - "connect"事件未触发客户端套接字