单元测试App.Config中的连接字符串被忽略:SQLExpress设置为LocalDB

时间:2015-10-27 20:52:50

标签: c# unit-testing entity-framework-6

我有大量的单元测试在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'..

当我将连接字符串设置回“thedatabase”时,它会重置为使用localdb和集成安全性。这就像它有一个别名或其他东西。

1 个答案:

答案 0 :(得分:1)

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

dc.SubmitChanges();

它击中了我,这个类使用的是LINQ to Sql而不是Entity Framework。不知何故,使用LINQ to Sql的类正在改变连接字符串并默认为(localdb),这是我们在编写该库时使用的。

我将类更改为使用Entity Framework,突然我的所有测试都开始重新考虑连接字符串。

这很奇怪,因为

  1. 旧的引用库实际上不再进行任何数据更新(其中的数据更新代码是遗留的,很久以来就放在别处)
  2. 旧库甚至没有对提供其连接字符串的数据类的有效引用
  3. 尽管如此,只是通过单元测试引用旧库导致连接字符串怪异。
相关问题