从Microsoft.AspNetCore.TestHost.TestServer获取连接字符串值

问题描述 投票:0回答:2

我有一个测试项目,我需要在测试类中获取连接字符串值

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);

    }
}
c# asp.net asp.net-core .net-core
2个回答
0
投票

您可以在测试主机上使用服务集合。例如:

var config = _testServer.Host.Services.GetRequiredService<IConfigurationRoot>();
var connectionString = config.GetConnectionString("Foo");

但是,您实际上应该将此用于所有服务,因此不要尝试新建您的上下文,只需执行以下操作:

var context = _testServer.Host.Services.GetRequiredService<AppDbContext>();

不需要连接字符串。


0
投票

假设您的测试服务器设置正确,您应该直接从服务器实例解析数据库上下文。像这样:

_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
}

从技术上讲,您还可以从测试主机解析配置并从中读取连接字符串,但是由于您正在进行集成测试,因此您应该通过手动创建数据库上下文来测试完全集成并且不要偏离现有设置。

© www.soinside.com 2019 - 2024. All rights reserved.