我想在Xunit中创建一个临时数据库来进行集成测试,但是当我尝试删除临时数据库时,会出现如下错误:
无法删除数据库"TempDatabase_[数字]",因为它正在使用中。
仅仅关闭和释放命令和连接似乎并不能解决问题。
以下是我测试失败的简化版本:
using System;
using System.Data.SqlClient;
using Xunit;
namespace Test
{
public class Test_Raw_Spec
{
[Fact]
public void PerformWorkInTemporaryDatabase()
{
string connectionStringTemplate = "Data Source=SQLEXPRESS;Initial Catalog={0};Integrated Security=SSPI;Connection Timeout=10";
int dbNum = (new Random()).Next() % 1000000;
int tblNum = (new Random()).Next() % 1000000;
string nameTempDb = $"TempDatabase_{dbNum}";
string nameTempTable = $"TempTable_{tblNum}";
var sqlConnection1 = new SqlConnection(string.Format(connectionStringTemplate, "master"));
var sqlCommand1 = new SqlCommand($"CREATE DATABASE {nameTempDb}", sqlConnection1);
sqlConnection1.Open();
sqlCommand1.ExecuteNonQuery();
sqlCommand1.Dispose();
sqlConnection1.Close();
sqlConnection1.Dispose();
var sqlConnection2 = new SqlConnection(string.Format(connectionStringTemplate, nameTempDb));
var sqlCommand2 = new SqlCommand($"CREATE TABLE {nameTempTable}(id int)", sqlConnection2);
sqlConnection2.Open();
sqlCommand2.ExecuteNonQuery();
sqlCommand2.Dispose();
sqlConnection2.Close();
sqlConnection2.Dispose();
var sqlConnection3 = new SqlConnection(string.Format(connectionStringTemplate, "master"));
var sqlCommand3 = new SqlCommand($"DROP DATABASE {nameTempDb}", sqlConnection3);
sqlConnection3.Open();
sqlCommand3.ExecuteNonQuery();
sqlCommand3.Dispose();
sqlConnection3.Close();
sqlConnection3.Dispose();
}
}
}
ALTER DATABASE [test] SET SINGLE_USER WITH ROLLBACK AFTER 5
将在5秒后强制关闭数据库中的所有其他连接(例如,池中的其他连接)。 - RichardPooling=false
,这最终也会清除连接池(请参见 https://dev59.com/c2w05IYBdhLWcg3w0VKa#22390350)。由于集成测试应该是所有测试的一个较小的子集,这对我来说也是一个可行的替代方案。 - VeeTheSecond