views:

548

answers:

3

When I try to run Unit Tests (mstest) I run into this issue.
The line of code:

_mainCnStr = System.Configuration.ConfigurationManager.
               ConnectionStrings["main"].ConnectionString;

Comes back as a null reference

It doesn't do this in the main UI project when I run it. What is the right method to get this connection string setting seen by the Unit Test project? I tried embedded as a resource. I tried Copy Always. What is the right combination of settings that will fix this for me?

+2  A: 

You should add an app.config to the unit test project. It won't automatically use the settings in UI application's app.config.

Mehrdad Afshari
Shouldn't I be able to embed my config into the assembly. I thought I had seen this before.
tyndall
huh. I copied it an still getting the error. weird
tyndall
Right click on the test project, add an "Application Configuration File" and copy the contents. It should work...
Mehrdad Afshari
ok figured that one out. but still copying this info to 2 other projects for testing seems a little weird.
tyndall
I guess any other compile option but None. Cancels the Copy Always.
tyndall
Config file is not *embedded* in the assembly, it's published along it with the name "[entryassembly].exe.config". Since the test project uses another entry assembly, it requires a separate file. And by the way, you probably want to test against a test database, for instance, rather than a production server.
Mehrdad Afshari
A: 

I'm assuming mstests are, like nunit tests, embedded in a seperate assembly which gets loaded by the testing application? In that case, you may need to create some test set-up code which loads in the configuration file.

John Christensen
+3  A: 

One thing to watch with MSTest (from the IDE at least); it doesn't run the tests in the regular output (bin) folder, and it doesn't respect the project's file inclusions ("Copy to Output Directory"). You often need to explicitly tell it (MSTest) which files to put into the test area. You will need to include the "app.config" in this list; either via the testrunconfig ("Deployment"), or by adding an attribute ([DeploymentItem]) to the affected test fixtures.

Marc Gravell
After put DeploymentItem("db.config") on top of test class, it worked! thanks.
Jirapong