2

我遇到了这个错误

An attempt to attach an auto-named database for file C:\<...>\Out\MessagesDB.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share..  

尝试编写一些单元测试来测试控制器。我相信问题在于测试试图不使用我在主项目中定义的数据库。所以我将测试中的连接字符串修改为

在我正在使用的测试项目的 App.config 中

<connectionStrings>
    <add name="MessagesDBConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\MessagesDB.mdf;Integrated Security=True;User Instance=True"
      providerName="System.Data.SqlClient" />
</connectionStrings>

然后通过执行覆盖 DataDirectory

AppDomain 域 = AppDomain.CurrentDomain;

        String currentDirectory = System.Environment.CurrentDirectory;
        String DataDirectory = currentDirectory.Substring(0, currentDirectory.IndexOf("TestResults")) + "Server\\App_Data";
        domain.SetData("DataDirectory", DataDirectory);
        db = new Server.Models.MessagesDBDataContext();

效果很好,但看起来像黑客。我应该怎么做?

编辑:

我今天又看了一眼这个可怕的混乱,基于 Nerd Dinner 示例,我从项目中的控制器中删除了对数据库的所有直接调用,并将它们移动到实现接口 (IRepository) 的存储库对象中。然后我创建了一个假的存储库对象,它也实现了 IRepository。我向每个控制器添加了一个构造函数,它允许传入要使用的 IRepository。然后更改默认控制器构造函数以初始化存储库。测试不再与数据库对话,因此它们更快且破坏性更小。

4

1 回答 1

6

标准方法是模拟数据库。这意味着您正在测试的类需要一个提供数据的参数,并且看起来像一个数据库连接。

在单元测试中,您实际上传递了一个提供硬编码数据的实现。

There are tools which can help you with this, for example by saving the results of a database query into a config file, so that you can set up the test with real data, but it will load quickly and never change because it is now saved in a file separate from the database. SnapDAL is one tool you can use for this.

于 2009-03-26T03:16:33.043 回答