单元测试应用程序配置中的连接字符串被忽略:SQLExpress被设置为LocalDB

本文关键字:SQLExpress 设置 LocalDB 单元测试 配置 连接 字符串 应用程序 | 更新日期: 2023-09-27 18:19:26

我有一堆在Visual Studio 2013中运行良好的单元测试。我不知道它是否相关,但我想不出还有什么可能改变。我已将我的项目移至VS2015。

现在,每当我运行单元测试时,所有使用数据上下文的测试都会失败,并显示一个错误,表明他们试图使用(localdb)''V11.0和集成安全性来访问数据库。

然而,我的开发数据库是打开的。''sqlexpress,并具有SQL登录名。

我浏览了每个配置文件,包括单元测试项目中的app.config,它们都指定了正确的数据库。如果我在代码中调试步骤,我可以到达创建数据上下文的行,检查其属性并查看连接字符串是否错误,但我看不到它来自哪里。

以下是我的测试项目app.config文件的相关部分:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <connectionStrings>
    <add name="speedEntitiesDev" connectionString="metadata=res://*/mydb.csdl|res://*/mydb.ssdl|res://*/mydb.msl;provider=System.Data.SqlClient;provider connection string=&quot;Server=.'sqlexpress;Database=thedatabase;User ID=theuser;Password=thepassword;Connection Timeout=30;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="Server=.'sqlexpress;Database=thedatabase;User ID=theuser;Password=thepassword;Connection Timeout=30;MultipleActiveResultSets=True" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>

当我进入单元测试时,这就是属性检查器所说的连接字符串的值:

"Data Source=(localdb)''v11.0;Initial Catalog=thedatabase;Integrated Security=True"

请注意,数据库名称是正确的,但其他一切都是错误的。

我以前确实有一个本地托管在localdb中的数据库,但在升级我的开发计算机后,我停止了使用它

更新:我发现,如果我在上面的文件中重命名连接,那么这会以不同的方式破坏测试。然后我得到一个错误,连接字符串没有找到:

System.InvalidOperationException: No connection string named 'speedEntitiesDev' could be found in the application config file..

对连接字符串的其他更改也会产生影响(例如,如果我更改数据库名称,则连接将转到新的数据库名称,并使用我提供的登录名和密码。)

System.Data.Entity.Core.EntityException: The underlying provider failed on Open. ---> System.Data.SqlClient.SqlException: Cannot open database "thedatabase123" requested by the login. The login failed. Login failed for user 'theuser'..

当我将连接字符串设置回"数据库"时,它会重置为使用localdb和集成安全性。这就像是有一个别名或其他什么。

单元测试应用程序配置中的连接字符串被忽略:SQLExpress被设置为LocalDB

在深入研究代码几天后,我注意到在每个失败测试的每个类引用的一个旧库中,有一个数据更新,写为:

dc.SubmitChanges();

我突然想到,这个类使用的是LINQ to Sql,而不是实体框架。不知怎的,使用LINQ to Sql的类更改了连接字符串,并默认为(localdb),这是我们在编写该库时使用的。

我将类改为使用实体框架,突然间,我的所有测试都开始重新考虑连接字符串。

这很奇怪,因为

  1. 旧的引用库实际上不再进行任何数据更新(其中的数据更新代码是遗留的,早就放在其他地方了)
  2. 旧库甚至没有对提供其连接字符串的数据类的有效引用
  3. 尽管如此,仅仅通过单元测试引用旧库就导致了连接字符串的怪异