5
votes

I would like to know the recommended approach to getting a connection string from a config file for my xUnit .net core test project.

I have set up a test project using the new Visual Studio 2017 xUnit Test project template for .net core. This project will run my integration tests that reference 2 different .net core class library projects - one of which will talk to the database using EF Core.

I understand that normally the connection string should not be set or accessed in a class library project - it should be the application that consumes the class library that should set the connection string.

However, in this case it appears that the xUnit test project is treated somewhat like a class library project. I have not seen any examples of how to set up some sort of config file and access that from the test project. How do I access the connection string from a config file so that my test project can consume my Datalayer class library project and pass in the appropriate connection string?

1
Do you excpliticly need a connection string in your tests or something like TestServer (msdn.microsoft.com/en-us/library/…) would suffice? - Ignas
See my solution below - thanks - Pacificoder

1 Answers

9
votes

I was able to access the connection string from my xUnit test project by creating a DbOptionsFactory class that returns a DbContextOptions object initialized with a connection string that it reads from an appsettings.json configuration file.

This requires a dependency on Microsoft.Extensions.Configuration

public static class DbOptionsFactory
{
    static DbOptionsFactory()
    {
        var config = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json")
            .Build();
        var connectionString = config["Data:DefaultConnection:ConnectionString"];

        DbContextOptions = new DbContextOptionsBuilder<MyDbContext>()
            .UseSqlServer(connectionString)
            .Options;
    }

    public static DbContextOptions<MyDbContext> DbContextOptions { get; }

}

appsettings.json

{   
  "Data": {
  "DefaultConnection": {
      "Name": "MyDbContext",
      "ConnectionString": "connection string goes here"
   }   
 }
}

When instantiating my DbContext I pass in the optionsBuilder object that has the connection string from the configuration file like so:

using (var context = new MyDbContext(DbOptionsFactory.DbContextOptions))
{  
     // access db here
}

Hope this helps anyone else that runs into the same issue.