How to use web.config when unit testing an asp .net application

Viewed 50403

I am starting out with unit testing, I have a method that uses the web.config for a connection string.

I was hoping to be able to use

[DeploymentItem("web.config")]

to get the web config file, this still leaves me with null reference exceptions (that'd be what I write my next test for).

How do I use the config file included with the project I am trying to test?

I am using the testing framework included in VS 2008, if that makes any difference.

Thanks

6 Answers

Unit test projects should have their own config file.

On a test project you can choose Add, New Item, Application Configuration File.

This file will behave exactly like a web.config, but then for your unit tests.

You will want your results to be well-defined and repeatable. To to this, you'll need to be working against known data so that you can clearly define both your normal cases and your boundary cases. In my work, this is always a specific server and dataset so the Unit testing module has the connection string built in. Others prefer using a connection string out of the Unit Testing project. I've never seen anyone recommend the use of the web site's config file! (development or otherwise)

If you need a connection string, you are not writing a unit test (assuming that you are using the connection string for going to database). Unit tests are not supposed to interact with outside environment. You will want to run all of them after each check in so they better run at the speed of light.

For a unit test, you will want to isolate your code from your database. Modify your tests (and the code you are testing if necessary) so that you will not need to go to database for testing them.

Related