Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 314
New Developer Avatar asked Jun 06 '13 06:06

New Developer


2 Answers

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.

like image 112
aquaraga Avatar answered Oct 29 '22 22:10

aquaraga


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

like image 40
boniestlawyer Avatar answered Oct 29 '22 20:10

boniestlawyer