[英]Get connection string value from Microsoft.AspNetCore.TestHost.TestServer
I have a test project, i need to get the connection string value in a test class 我有一个测试项目,我需要在测试类中获取连接字符串值
public class EmplyeesScenarios
{
private readonly TestServer _testServer;
private readonly AppDbContext _testService;
public EmplyeesScenarios()
{
_testServer = TestServerFactory.CreateServer<TestsStartup>();
var dbOption = new DbContextOptionsBuilder<AppDbContext>()
.UseSqlServer("//here i need to put the same connection string of _testServer")
.Options;
_testService = new AppDbContext(dbOption);
}
}
You can use the service collection on your test host. 您可以在测试主机上使用服务集合。 For example:
例如:
var config = _testServer.Host.Services.GetRequiredService<IConfigurationRoot>();
var connectionString = config.GetConnectionString("Foo");
However, you should actually be using this for all your services, so instead of trying to new up your context at all, just do: 但是,您实际上应该在所有服务中都使用它,因此,不要尝试完全更新上下文,而要做的是:
var context = _testServer.Host.Services.GetRequiredService<AppDbContext>();
No connection string needed. 不需要连接字符串。
Assuming that your test server is set up properly, you should just resolve your database context from the server instance directly. 假设您的测试服务器安装正确,则应该直接从服务器实例中解析数据库上下文。 Like this:
像这样:
_testServer = TestServerFactory.CreateServer<TestsStartup>();
// create service scope and retrieve database context
using (var scope = _testServer.Host.Services.CreateScope())
{
var db = scope.ServiceProvider.GetService<AppDbContext>();
// ensure that the db is created for example
await db.Database.EnsureCreatedAsync();
// add test fixtures or whatever
}
Technically, you could also resolve the configuration from the test host and the read the connection string out of it but since you are doing an integration test , you should actually test the full integration and not deviate from the existing setup by creating your database context manually. 从技术上讲,您还可以从测试主机解析配置,并从其中读取连接字符串,但是由于您正在执行集成测试 ,因此您应该实际测试完整的集成,并且不要通过手动创建数据库上下文来偏离现有设置。 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.