测试-缺少连接字符串 [英] Testing - Connection string is missing
问题描述
Visual Studio基于一种方法(右键单击添加测试)为我创建了一个单元测试项目。当我尝试访问数据库时,出现异常。运行此代码以查看我的连接是什么:
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"];
但是 connStringSettings
为空。经检查,ConnectionStrings集合只有一个计数。似乎不是从我的web.config中读取。
but, connStringSettings
is null. Upon inspection, ConnectionStrings collection has a count of only one. It seems to not be reading from my web.config.
我的DAL是隔离的,无法通过代码设置其连接字符串。它的连接字符串在这样的代码中设置:
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;
}
我该如何解决?
推荐答案
将 App.config
文件添加到单元测试项目中,然后从 Web.config
复制连接字符串。
Add an App.config
file to your unit testing project and copy over the connection string from the Web.config
.
虽然添加配置将解决当前的问题,但仍然会根据实际的数据库连接进行单元测试,这并不是很好。解决此问题的更好方法是完全模拟DAL,并将其传递给使用它的服务。
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提供了有关此处。设置需要花费更多时间,但可以使测试更加全面和完整。
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.
这篇关于测试-缺少连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!