我正在尝试创建一个单元测试项目,以确保项目中的所有迁移都能成功地允许向上和向下迁移。
我试图通过创建两个单元测试来实现这一目标。
设定:
这是我的单元测试设置。我有一个连接字符串,它是所有这些测试使用的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表明数据库上存在“休眠”进程,该进程是“AWAITING COMMAND”,留在数据库中。这意味着我的测试的TearDown将无法删除临时数据库,因为“数据库正在使用中”。
通过跑步者我似乎无法找到关闭此连接的方法,我试图更改所涉及的所有组件的超时,并尝试关闭连接字符串上的“池化”,但两者都没有工作。
有没有办法可以关闭此连接或确保关闭它?
由于
答案 0 :(得分:1)
由于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);
}
我还假设,没有处理处理器是挂断连接的原因。