unable to read appsettings when unit testing

While you can define the app settings in another config file for your unit test project, unit testing to interfaces using dependency injection may help break down the areas that your unit tests will be covering into more manageable portions.

So you could have your configuration interface like:

public interface IConfiguration
{
    public string Host { get; set; }
}

your class to test would accept an IConfiguration class as a parameter (usually to your constructor) like this:

public class MyClass
{
    IConfiguration _config;
    public MyClass(IConfiguration config)
    {
        _config = config;
    }

    public void MyMethodToTest()
    {
    }
}

Then your test can use the interface to pass in the configuration rather than depending on an external configuration file that can potentially change and affect your unit test:

[Test]
public void Testing_MyMethodToTest()
{
    // arrange
    var config = new Configuration { Host = "My Test Host" };
    // act
    new MyClass(config).MyMethodToTest();
    // Add assertion for unit test
}

And your actual implementation would create your configuration class, load it with the value(s) from the appsettings and pass that into your implementation


You should have an app.config created for your unit test project. The app.config of your console application will not be consulted when you're running the unit tests.