Reputation: 20066
I am totally stunned as why one of my unit tests is failing. It is a simple test to see if the correct connectionstring is returned. My App.config looks like this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<compilation defaultLanguage="c#" debug="true" />
</system.web>
<connectionStrings>
<add name="DbConnectionString" connectionString="Test_HighOnCoding_Db" />
</connectionStrings>
</configuration>
And here is my simple unit test which always throws null exception:
[TestFixture]
public class when_retrieving_database_name_from_config
{
[Test]
public void should_get_the_correct_database_name()
{
var dbName = ConfigurationManager.ConnectionStrings["DbConnectionString"].ConnectionString;
// dbName is always null
Assert.AreEqual("Test_HighOnCoding_Db",dbName);
}
}
Upvotes: 1
Views: 3273
Reputation: 11
It is a simple fix - put the app.config in your test project.
Because you are running from a test, the app.config needs to be in your test project, and NOT with your actual program project.
When executing your test, the context of the running application is from your test assembly, so ConfigurationManager.ConnectionStrings will be looking ONLY in your test project bin folder for YourTestAssembly.dll.config (which is auto generated from your app.config in you test project folder).
Upvotes: 1
Reputation: 14755
if your testdll is MyTests.dll your app.config in that sub-projet will become MyTests.dll.config. Unfortunately nunit wants "MyTests.config" (without the ".dll.")
to solve this issue
now you can run your unittest by opening "MyTests.nunit"
Upvotes: 0
Reputation: 40150
My original answer does not apply per your comment below.
One thing I'll suggest checking, then; Is your app.config
file being moved into the directory with your program, and being renamed to the same as the program, with .config added?
So, program.exe
has program.exe.config
as the config file?`
It looks like you have a Web application here; if so, your configuration file should be web.config
rather than app.config
. Then, you should be using the WebConfigurationManager
from the System.Web.Configuration
namespace.
Upvotes: 5