New Developer
New Developer

Reputation: 3305

unable to read appsettings when unit testing

I have C# console application. One of its function reading appconfig value and do some work.

string host = ConfigurationManager.AppSettings["Host"]  

So I wrote NUNIT test for my console application. Unit testing project was created using class library.

But my unit test is fail now . Because it is not reading my app settings (indicates no app settings). What is the reason for this.
When I run my console app, it is reading app settings correctly.

Upvotes: 24

Views: 26344

Answers (4)

Walter
Walter

Reputation: 119

It seems like a Visual Studio version problem. I have opened the same project in different versions of Visual Studio.

  • VS 2017 -> appsettings not found
  • VS 2019 (16.4.0) -> appsettings found

VS2019 screenshot, as you can see the Test and the appsettings are placed in different folders.

VS2019, as you can see the Test and the appsettings are placed in different folders.

Upvotes: 1

Developer Sheldon
Developer Sheldon

Reputation: 2160

Another solution can be as simple as copy all the app settings json file into the build folder of your unit testing project if you are just use the same files. Sometimes in Rider, it just didnt copy, I have do it manually.

Upvotes: 0

boniestlawyer
boniestlawyer

Reputation: 707

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

Upvotes: 11

aquaraga
aquaraga

Reputation: 4168

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.

Upvotes: 34

Related Questions