我正在编写集成测试来验证我的存储库中的行为。我遇到的问题是我想为每个测试从一个干净的数据库开始。我设法通过如下编写设置来做到这一点:
[SetUp]
public void SetUp()
{
_applicationContext = new TestApplicationContext();
_applicationContext.Database.Connection.Close();
_applicationContext.Database.Delete();
_applicationContext.Database.Create();
_tenantRepository = new TenantRepository(_applicationContext);
_userRepository = new UserRepository(_applicationContext);
}
TestApplicationContext 将数据库名称设置为 TestDatabase。
在我想检查实际数据库以获取我的测试结果之前,这一切正常。然后我建立从 MSSQL 服务器到同一个数据库的连接,该连接不会关闭,直到我:
- 关闭 MSSQL 服务器
- 使用“关闭所有连接”选项删除数据库
我找到的唯一方法是通过 SQL 命令。也许是因为我对 MSSQL 的了解不多,但我有点希望有一个“关闭连接”按钮/选项。
如何从 MSSQL 服务器关闭与数据库的连接? 或者,有没有一种方法可以从 C# 以编程方式执行此操作?
更新:
可能我说的不是很清楚。但是在我打开 MSSQL 并查看表的内容后,测试 SetUp 失败了。这是因为 MSSQL 还创建了到 TestDatabase 的连接,而我的集成测试无法关闭那个连接。因此,我正在寻找一种解决方案,允许我关闭从 MSSQL 服务器创建的连接。
请您参考如下方法:
如果不是删除并重新创建整个数据库,而是删除并重新创建选定的(或所有表),则可以解决连接问题。
您可以创建一个小脚本,它将以您不需要硬编码表名的方式为您完成: http://www.apexure.com/blog/2010/07/29/delete-all-tables-in-sql-server-database/
或者,Julia Lerman 在她的书“Programming Entity Framework:Code First”中提到了这种更成熟形式的方法,作为自定义数据库初始化程序合并:
As well as writing your own custom initializers, you can also find initializers that other people have created. One example of this is available in the EFCodeFirst.CreateTablesOnly NuGet package. This initializer will allow you to drop and create the tables in an existing database, rather than dropping and creating the actual database itself. This is particularly useful if you are targeting a hosted database where you don’t have permission to drop or create the entire database.
