reZach
reZach

Reputation: 9489

C# Injecting ConfigurationManager within unit tests

I've searched around and no answers have worked for me. I have 2 ASP.NET projects, one of them being my project, the other being a project containing unit tests.

# Projects
Project.Core
    ...
    secretConnectionStrings.config
    Web.config

Project.Tests

In Project.Core, I have a method that requests both a connection string (from secretConnectionStrings.config and an app setting from the web.config file. Executing on it's own, the correct values are pulled from both of these config files. However, I want to test this within my unit test.

My test looks like this (within Project.Tests):

[TestClass]
public class TestUserController
{
    [TestMethod]
    public void Post_ShouldReturnNewUser()
    {
        var controller = new UserController();

        var result = controller.Post() as User;
        Assert.AreNotEqual(result, null);
    }
}

The line it bombs out on is this

string cacheConnection = ConfigurationManager.ConnectionStrings["RedisCache"].ConnectionString;

System.NullReferenceException: Object reference not set to an instance of an object

I've tried adding web.config and secretConnectionStrings.config as a link in my Project.Tests solution. That hasn't worked, and I do not want to interface to my web.config (I want the values as they are saved in Project.Core). Is there a solution where I can pull values from Project.Core's web.config into my unit test?

Upvotes: 0

Views: 1987

Answers (1)

Keith Payne
Keith Payne

Reputation: 3082

The project containing the unit tests will need its own config file for the ConfigurationManager to pull in the connection strings. The best way to set this up and the keep only 1 copy of the config file is to add the same file into each project that needs it, but add it as a linked file:

Add Linked File

Don't forget to set the file properties so that it deploys with the executable code: Build Action

And add it as a deployment item to your test fixture(s):

[TestClass]
[DeploymentItem(@"db.config")]
public class MyTestFixture { ... }

Now, if you want to have centralized connection strings in two differently-named config files (app.config & web.config), then you can place them in a third file db.config and import that file into each of the other config files:

db.config

<connectionStrings>
    <add name="testDb" connectionString="data source=(localdb)\v11.0;..."
        providerName="System.Data.SqlClient" />
</connectionStrings>

app.config / web.config

<connectionStrings configSource="db.config" />

Make sure to set Copy To Output Directory for the imported config files in addition to your app.config or web.config and add them as deployment items to the test fixture with the attribute.

Upvotes: 1

Related Questions