使用xunit在.NET Core集成测试中获取数据库连接字符串

时间:2018-09-16 18:29:23

标签: c# asp.net-core .net-core xunit.net

我正在为.net核心项目进行集成测试。我需要访问集成测试数据库的连接字符串。

我将基础项目用作参考并使用其启动文件。但是我遇到了这个错误

System.ArgumentNullException : Value cannot be null.
Parameter name: connectionString at Npgsql.EntityFrameworkCore.PostgreSQL.Utilities.Check.NotEmpty(String 
value, String parameterName) in 
/home/roji/projects/EFCore.PG/src/EFCore.PG/Utilities/Check.cs:line 99   
at Microsoft.EntityFrameworkCore.NpgsqlDbContextOptionsExtensions.UseNpgsql(DbContextOptionsBuilder optionsBuilder, String connectionString, Action`1 npgsqlOptionsAction) in /home/roji/projects/EFCore.PG/src/EFCore.PG/Extensions/NpgsqlDbContextOptionsExtensions.cs:line 49
at SurveyAPI.Startup.<ConfigureServices>b__4_1(DbContextOptionsBuilder options)

我的TestClientProvider类

public class TestClientProvider
{
    public HttpClient Client { get; private set; }

    public TestClientProvider()
    {   
        var server = new TestServer(new WebHostBuilder().UseStartup<Startup>());

        Client = server.CreateClient();
    }
}

测试班

public class UnitTest1
{

    [Fact]
    public async Task Test_Get()
    {
        var client = new TestClientProvider().Client;

        var response = await client.GetAsync("/api");

        response.EnsureSuccessStatusCode();

        Assert.Equal(HttpStatusCode.OK, response.StatusCode); 
    }
}

如何使测试使用我当前的数据库?

1 个答案:

答案 0 :(得分:1)

我通过获取appsettings.json文件并在TestProvider类中配置数据库连接来解决此问题。

public class TestClientProvider
{
    public HttpClient Client { get; private set; }

    public TestClientProvider()
    {   
        IConfigurationRoot configuration = new ConfigurationBuilder()
            .SetBasePath(AppContext.BaseDirectory)
            .AddJsonFile("appsettings.json")
            .Build();

        WebHostBuilder webHostBuilder = new WebHostBuilder();
        webHostBuilder.ConfigureServices(s => s.AddDbContext<DatabaseContext>(options => options.UseNpgsql(configuration.GetConnectionString("DefaultConnection"))));
        webHostBuilder.UseStartup<Startup>();

        var server = new TestServer(webHostBuilder);

        Client = server.CreateClient();
    }
}