0

I have a .NET Core Web API project which already has an appsettings.json file, but I want to add the same thing to my corresponding xUnit project.

I added an appsettings.json file in the root of the project project files

And the contents of the appsettings.json is

{
    "DatabaseType" : "MySql",
    "ConnectionStrings" : {
    "CycleTrackingDb": "connection_string_here"
    }
}

The problem I'm having is when I call ConfigurationManager.ConnectionStrings["CycleTrackingDB"] and ConfigurationManager.AppSettings["DatabaseType"] it comes back as NULL or an empty string.

I set up xUnit using the Class Fixtures section of the xUnit guide https://xunit.github.io/docs/shared-context.html

In my DatabaseFixture is this

public class DatabaseFixture : IDisposable
{
    public Context Context { get; private set; }

    public DatabaseFixture()
    {
        Context = new Context(DatabaseOptionsFactory.DbContextOptions);
    }

    public void Dispose()
    {
    }
}

All my test classes will inherit from this one:

[Collection("Database collection")]
public class CycleTargetTrackerTest
{
    protected Context Context { get; }

    public CycleTargetTrackerTest()
    {
        Context = new DatabaseFixture().Context;
    }
}

The DatabaseOptionsFactory is just a static class that should read in the settings of the appsettings.json file, with the first 2 lines of the static constructor being the following, which will use the output to set up the context

var databaseType = (DatabaseType)Enum.Parse(typeof(DatabaseType), Config.Configuration.Settings["DatabaseType"]);
var connectionString = ConfigurationManager.ConnectionStrings["CycleTrackingDB"];

These both return empty.

EDIT I managed to get it to read in the appsettings.json file. I followed this guide here: Read appsettings json values in .NET Core Test Project, but now what I'd like to do is load the settings in the same way as System.Configuration.ConfigurationManager. Is there a way to do this?

Omar.Ebrahim
  • 862
  • 1
  • 10
  • 30
  • Can you explain how you launch tests? – vernou Oct 28 '18 at 15:11
  • Amended my question to include test setup – Omar.Ebrahim Oct 28 '18 at 15:21
  • What is 'same way as System.Configuration.ConfigurationManager'? It's load automatically? – vernou Oct 28 '18 at 15:37
  • Apologies, I guess what I meant was convert the connections strings section to a ConnectionStringsSection, I realise there's not a way to do this, and if I did want to do this I'd load the settings into custom settings section classes. It does load now, though so it does work – Omar.Ebrahim Oct 28 '18 at 15:44

0 Answers0