Fluent Migrator单元测试:保持连接
本文关键字:连接 Migrator 单元测试 Fluent | 更新日期: 2023-09-27 18:06:29
我正在尝试创建一个单元测试项目,以确保在项目中进行的所有迁移将成功地允许上下迁移。
我试图通过创建两个单元测试来实现这一点。
设置:
- NUnit
- EntityFramework
- LocalDBFluentMigrator,跑步者
这是我的单元测试设置。我有一个连接字符串,它是所有这些测试使用的LocalDb数据库(v11)的链接:
[TestFixture]
public class MigrationTestHandler
{
private string ConnectionString
{
get
{
return ConfigurationManager.ConnectionStrings["MigrationDatabase"].ConnectionString;
}
}
[SetUp]
public void SetUp()
{
var blankContext = new DbContext(ConnectionString);
blankContext.Database.Delete();
blankContext.Database.Create();
}
[TearDown]
public void TearDown()
{
var blankContext = new DbContext(ConnectionString);
blankContext.Database.Delete();
}
[Test]
public void CanUpgradeDatabase()
{
var migrator = new MigrationRunnerHandler(ConnectionString);
migrator.Migrate(runner => runner.MigrateUp());
}
[Test]
public void CanRollbackDatabase()
{
var migrator = new MigrationRunnerHandler(ConnectionString);
migrator.Migrate(runner => runner.MigrateUp());
migrator.Migrate(runner => runner.Rollback(int.MaxValue));
}
}
这是我用来调用所有迁移的迁移运行程序处理程序类:
public class MigrationRunnerHandler
{
private readonly string _connectionString;
private FluentMigrator.Runner.MigrationRunner Runner { get; set; }
public MigrationRunnerHandler(string connectionString)
{
_connectionString = connectionString;
}
private class MigrationOptions : IMigrationProcessorOptions
{
public bool PreviewOnly { get; set; }
public int Timeout { get; set; }
public string ProviderSwitches { get; set; }
}
public void Migrate(Action<IMigrationRunner> runnerAction)
{
var factory = new SqlServer2008ProcessorFactory();
var assembly = Assembly.GetExecutingAssembly();
var announcer = new TextWriterAnnouncer(s => Console.Write(s));
var migrationContext = new RunnerContext(announcer)
{
TransactionPerSession = true,
};
var processor = factory.Create(_connectionString, announcer, new MigrationOptions
{
PreviewOnly = false,
Timeout = 5
});
Runner = new FluentMigrator.Runner.MigrationRunner(assembly, migrationContext, processor);
runnerAction(Runner);
}
}
问题是,在我的测试的TearDown, FluentMigrator似乎持有到数据库的连接。在数据库上运行sp_who将显示数据库上有一个"休眠"进程,该进程是"等待命令",它留在数据库上。这意味着我的测试的TearDown将无法删除临时数据库,因为"数据库正在使用中"。
通过跑步者,我似乎找不到一种方法来关闭这个连接,我试图改变所涉及的所有组件的超时,并试图在连接字符串上关闭"池",但都没有工作。
是否有一种方法可以关闭此连接或确保它已关闭?
谢谢
由于IMigrationProcessor实现了IDisposable,我们应该这样使用它:
using(var processor = factory.Create(_connectionString, announcer, new MigrationOptions
{
PreviewOnly = false,
Timeout = 5
}))
{
Runner = new FluentMigrator.Runner.MigrationRunner(assembly, migrationContext, processor);
runnerAction(Runner);
}
我还假设,没有释放处理器是挂起连接的原因。