我正在 .NET Core 中编写一些集成测试,但我无法运行测试,因为连接字符串返回 null。我的代码在 Startup.cs
在下面,我确实复制了appsettings.json
根据 these answers 到测试项目.我错过了什么?
编辑:我想出了如何逐步完成单元测试,并且环境被设置为生产环境,即使我明确设置了 ASPNETCORE_ENVIRONMENT
至 development
在测试和主要项目中。我正在 Debug模式下构建。我不知道我应该在哪里设置它。无论哪种方式,它都应该引入一个值而不是 null——两者都是 appsettings.development.json
和 appsettings.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/