You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 6测试本地通过但GitHub Actions执行失败,求解决方法

解决方案

1. 强制请求使用目标文化

在创建测试客户端时,给请求头加上法语标识,确保页面加载对应语言的内容:

var client = _factory.WithWebHostBuilder(builder =>
{
    builder.ConfigureTestServices(services =>
    {
        services.AddScoped<ILinkRepository, TestLinkRepository>(serviceProvider =>
        {
            return new TestLinkRepository(_links, null);
        });
    });
})
.CreateClient(new WebApplicationFactoryClientOptions
{
    DefaultRequestHeaders = { ["Accept-Language"] = "fr-FR" }
});

2. 配置测试服务的默认本地化文化

在测试的服务配置中,直接指定应用默认使用法语文化,避免环境差异影响:

builder.ConfigureTestServices(services =>
{
    services.AddScoped<ILinkRepository, TestLinkRepository>(serviceProvider =>
    {
        return new TestLinkRepository(_links, null);
    });

    // 固定本地化默认文化为法语
    services.Configure<RequestLocalizationOptions>(options =>
    {
        var supportedCultures = new[] { "fr-FR" };
        options.SetDefaultCulture(supportedCultures[0])
               .AddSupportedCultures(supportedCultures)
               .AddSupportedUICultures(supportedCultures);
    });
});

3. 确保本地化资源文件正确部署

检查项目的.csproj文件,确认法语资源文件(.resx)被正确嵌入或复制到输出目录,避免GitHub Actions环境下资源丢失:

<!-- 将资源文件设置为嵌入资源 -->
<EmbeddedResource Include="Resources\*.resx" />
<!-- 或者设置为复制到输出目录 -->
<Content Include="Resources\*.resx">
    <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>

4. 统一测试环境的配置文件

如果应用在不同环境使用不同配置,在测试中指定加载测试专用的配置文件,消除环境配置差异:

builder.ConfigureAppConfiguration((context, config) =>
{
    // 清除默认配置,加载测试专属配置
    config.Sources.Clear();
    config.AddJsonFile("appsettings.Test.json", optional: false, reloadOnChange: true);
});

以上方案中,最常见的问题是GitHub Actions默认系统文化与本地不一致,导致页面标题语言不符,优先尝试前两种方法即可解决大多数场景。

内容的提问来源于stack exchange,提问作者mathdx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 03:00:06