Testing - Connection string is missing

2019-02-16 07:01发布

问题:

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?

回答1:

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



回答2:

Excellent this worked for me. I have added App.config file under unit test project. But make sure that we shoud follow the synatx otherwise it will throw exception.

<connectionStrings>

    <add name="test" connectionString="" providerName="System.Data.SqlClient" />

    <add name="db" connectionString=""" providerName="System.Data.SqlClient"/>

</connectionStrings>



回答3:

Add a connection string in the unit test's app.config file. The unit test project isn't going to have access to your web project's web config.



回答4:

Another solution is to go to the solution property pages (solution->properties)

Startup Project - check the single startup project is the one with the config.

Select, ok - done.