我正在为ASP.NET核心WebAPI创建集成测试。我试图使TestServer使用的是真实的,而不是内存中的sql-server数据库。
第一个问题是,WebHostBuilder没有在"connectionstring.json“中看到连接字符串,所以我将连接字符串cofnig移到"appsettings.json”。现在,WebHostBuilder从appsettings.json文件加载连接字符串,但在执行查询时它不会从server数据库加载任何数据(返回空集合)。当我正常运行它(不是作为测试服务器)并通过邮递员时,它就是这样做的。
我的问题是:“是否可以让TestServer使用sql-server数据库,以及如何做到?”
我在这里发现了一个类似的问题,call api Test server : .net core API integration tests,但没有人回答如何使TestSever与sql-server数据库一起工作。
TestServer:
_server = new TestServer(WebHost.CreateDefaultBuilder()
.UseEnvironment("Development")
.ConfigureAppConfiguration(AddConfigFiles)
.UseStartup<Startup>()
);AddConfigFiles方法:
public static void AddConfigFiles(WebHostBuilderContext hostingContext, IConfigurationBuilder config)
{
var env = hostingContext.HostingEnvironment;
config
.AddJsonFile("connectionstrings.json", optional: true)
.AddJsonFile($"connectionstrings.{env.EnvironmentName}.json", optional: true)
.AddJsonFile("appsettings.json", optional: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
config.AddEnvironmentVariables();
}连接字符串
"Data Source={MyServerName};Initial Catalog={MyDatabaseName};Integrated Security=True;"发布于 2019-02-26 10:39:54
是的,如果您希望看到完整的设置,请查看以下答案:https://stackoverflow.com/a/54858071/2482439
在本例中,所使用的数据库为SQLite,但您可以将DatabaseType配置更改为使用Server或任何其他配置。
请记住,配置文件必须位于当前正在执行测试的测试项目的文件夹中,其范围、路径由该文件定义。因此,如果您有Project.Integration.Tests,则在根文件夹中需要有connectionstrings.Development.json和appsettings.Development.json。
另外,您可能应该为您真正需要的配置设置必需的true。
https://stackoverflow.com/questions/50115249
复制相似问题