c# - 测试类找不到连接字符串

标签 c# asp.net-core asp.net-core-mvc .net-core

我正在 .NET Core 中编写一些集成测试,但我无法运行测试,因为连接字符串返回 null。我的代码在 Startup.cs在下面,我确实复制了appsettings.json根据 these answers 到测试项目.我错过了什么?

编辑:我想出了如何逐步完成单元测试,并且环境被设置为生产环境,即使我明确设置了 ASPNETCORE_ENVIRONMENTdevelopment在测试和主要项目中。我正在 Debug模式下构建。我不知道我应该在哪里设置它。无论哪种方式,它都应该引入一个值而不是 null——两者都是 appsettings.development.jsonappsettings.production.json有一个字符串,通用的 appsettings.json如下(与开发相同)。

编辑 2: 测试项目似乎完全忽略了我设置的任何配置。它正在运行主项目的 Startup不管我是否告诉它。我删除了对它的所有引用,但它仍在尝试运行它。

Startup.cs :

public IConfigurationRoot Configuration { get; }

public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", true, true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", true)
        .AddEnvironmentVariables();

    Configuration = builder.Build();
}

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<MyContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("MyDatabase")));
}

appsettings.json :

{
  "ConnectionStrings": {
    "MyDatabase": "Server=localhost;Database=MyDevLocal;Trusted_Connection=True;"
  }
}

最佳答案

这对我有用

var builder = new WebHostBuilder() .UseStartup<Startup>() .UseSetting("ConnectionStrings:DefaultConnection", /*Your conn string*/)

关于c# - 测试类找不到连接字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39059929/

相关文章:

c# - 如何防止 for 循环中覆盖数组条目?

c# - 将项目添加到 EF Core 中的集合导航属性

c# - 在哪里可以记录 ASP.NET Core 应用程序的启动/停止/错误事件?

c# - ASP.NET Core 3.1 Web 应用程序在 IIS Express 上运行时抛出错误 500.30,但在使用 dotnet watch run 时不会抛出错误

c# - 在同一个 MVC 6 Controller 中组合 API Controller 调用和 Controller 调用

c# - 我可以使用完整版的 Visual Studio 2010 来开发 Windows 7 Phone 应用程序而不是下载包吗

c# - 使用 Shift+F5 终止运行后返回编码 Pane 的 Visual Studio 快捷方式

c# - 如何解决 ASP.NET Core MVC 中的 'View not found' 错误?

asp.net-core - 移动特定 View /设备检测

C#快速像素渲染