执行回滚 - 存储库集成测试

时间:2010-08-21 14:57:47

标签: c# .net database entity-framework

我想实现我的Entity Framework驱动的存储库的集成测试。问题是如何在测试完成后回滚数据库状态。目前我正计划在测试SetUp上启动事务并在测试TearDown时将其回滚。除手动数据库清除外还有其他解决方案吗?

5 个答案:

答案 0 :(得分:24)

我们在使用MSTest时在集成测试中执行此操作。我们使用TransactionScope并在基类中实现测试设置和拆解。这允许您在事务中运行所有集成测试。基类看起来很像这样:

public class IntegrationTestsBase
{
    private TransactionScope scope;

    [TestInitialize]
    public void Initialize()
    {
        this.scope = new TransactionScope();
    }

    [TestCleanup]
    public void TestCleanup()
    {
        this.scope.Dispose();
    }
}
祝你好运。

答案 1 :(得分:5)

我认为你走在正确的轨道上......

Here's an example doing the same with Linq To SQL that you can tweek for yourself.

This link describes three options

  • 交易
  • 重建数据库
  • 使用SQL Server快照

该帖子接着描述了最快的事务与单个会话相关联,并且可以创建一些真正的问题/限制。如果你能使用......

重建数据库很慢,但绝对可行,但使用快照很快并且可以解决事务限制。

如果您需要在自动化测试try this from the same blogger中获得非常高的性能。他描述了使用MS Distributed Transaction Coordinator来消除单个会话的事务限制。

答案 2 :(得分:4)

在TearDown中设置和处置时打开TransactionScope的问题是你没有测试提交!

答案 3 :(得分:2)

这可能是最简单的方法,另一种方法是在SetUp重建数据库。

答案 4 :(得分:0)

最好的方法是交易方法。我提供的链接包含一小段步行通过。我接触过的几乎所有企业解决方案都使用基于事务的方法。请务必查看文章底部的链接,这些链接指向Microsoft有关实体框架交易的文档的链接。上面列出的其他选项在清理测试事务的简单概念中竞争过度。构建数据库或使用服务器快照对此问题完全过分。 TransactionScope甚至不执行该事务,导致集成测试未完成。

实施交易

这将在每次测试开始之前创建一个事务,并在每次测试结束后回滚事务。

[TestClass]
public class TransactionTest
{
  protected EntitiesV3 context;
  protected DbContextTransaction transaction;

  [AssemblyInitialize]
  public static void AssemblyStart(TestContext testContext)
  {
    RetryDbConfiguration.SuspendExecutionStrategy = true;
  }

  [TestInitialize]
  public void TransactionTestStart()
  {
    context = new EntitiesV3();
    transaction = context.Database.BeginTransaction();
  }

  [TestCleanup]
  public void TransactionTestEnd()
  {
    transaction.Rollback();
    transaction.Dispose();
    context.Dispose();
  }

  [AssemblyCleanup]
  public static void AssemblyEnd()
  {
    RetryDbConfiguration.SuspendExecutionStrategy = false;
  }
}

Great quick walk through on transactional rollback/cleanup approach