Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing - Connection string is missing

Tags:

Visual studio created a unit test project for me based on a method (right-click add test). When I try to access the database, I get an exception. Ran this code to see what my connection was:

ConnectionStringSettings connStringSettings = ConfigurationManager.     ConnectionStrings["myConnectionString"]; 

but, connStringSettings is null. Upon inspection, ConnectionStrings collection has a count of only one. It seems to not be reading from my web.config.

My DAL is isolated and cannot have its connection string set through code. Its connection string is set in code like this:

set {     value = System.Configuration.ConfigurationManager.         ConnectionStrings["myConnectionString"].ConnectionString; } 

How can I resolve this?

like image 955
O.O Avatar asked Feb 27 '12 19:02

O.O


People also ask

Where is the connection string located?

Typically, the connection string will be stored in a configuration file somewhere within the application or web server. This connection string is typically stored in plain text to make it easy to edit and easy to change as the application is moved from development, to QA, to staging, and to production.


1 Answers

Add an App.config file to your unit testing project and copy over the connection string from the Web.config.

Update: Better Solution

While adding a config will solve the immediate problem, it still results in unit tests depending on an actual database connection, which is not great. The better way to solve this problem is to mock the DAL entirely and pass that into the services which are using it.

Microsoft provides some guidance on that here. It takes a little more time to setup, but it allows tests to be much more contained and complete.

I have had success using MockQueryable for mocking individual tables within a test data context.

like image 134
eouw0o83hf Avatar answered Sep 27 '22 20:09

eouw0o83hf