Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
267 views
in Technique[技术] by (71.8m points)

c# - Testing - Connection string is missing

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...