views:

238

answers:

3

When i run a simple test on connection to DB check i receive an error in NUnit:

[Test]
public void TestConn()
{
    string  connectionString = ConfigurationManager.ConnectionStrings["FertigungRead"].ConnectionString;
    SqlConnection connection = new SqlConnection(connectionString);
    connection.Open();
    Assert.AreEqual(ConnectionState.Open, connection.State);
    connection.Close();
 }

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

on line :

connectionString = ConfigurationManager.ConnectionStrings["FertigungRead"].ConnectionString;

Can i use ConfigurationManager in tests?

+3  A: 

Yes, you can. You need to be sure that any configuration you are referencing in your tests actually exist in the app.config of the test project.

In other words, the project where your test is in, does not have a connection string "FertigungRead" defined in its app.config.

One way to do this is to add the app.config of the system under test to the test project as a link, this way any changes happen on both projects.

Oded
+1  A: 

Your unit tests should still work as long as you have the same configuration for your test project as for your main project.

I'd suggest using a pre-build event in your test project to copy your application's configuration file over to the test project. This saves having to maintain two sets of configuration.

copy $(SolutionDir)path-to-main-project\Web.config $(ProjectDir)App.config

Richard Ev
A: 

Why do you need a unit test to see if SqlConnection works? You should test your code, not Microsoft's. I don't really see the point in checking if the connection string is correct either in your unit tests. The configuration used by the unit tests isn't the same as what will be used by your production code.

In general, though, if you need some configuration data for unit tests, create an app.config file in the test project. Populate the appSettings and connectionStrings elements, etc. with appropriate values for your test environment. Don't bother testing whether ConfigurationManager or SqlConnection works, though. You'll just be creating code that you have to maintain, but that doesn't actually verify any of the production code you are writing.

tvanfosson