Reputation: 441
I'm doing integration tests for my .net core project.I need to get access to a connection string for my integration tests database.
I am using my base project as reference and using its Startup file. But I am getting this error
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)
My TestClientProvider class
public class TestClientProvider
{
public HttpClient Client { get; private set; }
public TestClientProvider()
{
var server = new TestServer(new WebHostBuilder().UseStartup<Startup>());
Client = server.CreateClient();
}
}
the test class
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);
}
}
How to make the tests use my current database ?
Upvotes: 1
Views: 2742
Reputation: 441
I have fixed this issue by getting the appsettings.json file and configuring the database connection in TestProvider class.
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();
}
}
Upvotes: 2